Search code examples
phpmysqlclassscopecode-reuse

PHP Class Database Connection Scope Issue


For a new project that I'm doing in PHP I've created an SQLMethods class to connect to the database and perform queries. Tonight was the first night that I actually got to test it (I wrote it a week or so ago and forgot about it) and an unexpected error occured: When it was calling my ExecuteQuery() function, it wouldn't use the database I selected in the constructor.

The constructor:

    public function SQLMethods() {
        $SQLConnection = mysql_connect($SQLDBAddress, $SQLUserName, $SQLPassword);

        if (!$SQLConnection) {
            die('Could not connect: ' . mysql_error());
        }

        mysql_select_db($SQLDB, $SQLConnection);
    }

The function in question:

    public function ExecuteQuery($Query) {
        mysql_query($Query, $SQLConnection) or die('Could not perform query: ' . mysql_error());
    }

Does anyone see what the issue might be? Does the connection close after the constructor completes?


Solution

  • you should declare $SQLConnection in your class, and you should refer to it as

     $this->SQLConnection
    

    and not simply $SQLConnection.