PHP Class Database Connection Scope Issue

痴心易碎 提交于 2019-12-11 04:22:48

问题


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?


回答1:


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

 $this->SQLConnection

and not simply $SQLConnection.




回答2:


$SQLConnection doesn't exist within the ExecuteQuery method.

You can either pass it directly as a parameter to ExecuteQuery, or add an sqlConnection class property that is set in the constructor and accessed as $this->sqlConnection inside your class methods.




回答3:


The variable $SQLConnection ExecuteQuery() is trying to use is created within another scope. (The SQLMethods function).

The connection closes when the PHP script has done its work or if you close it yourself (if the connection is made within that script)

You should skip the $SQLConnection variable within ExecuteQuery as stated by the php.net documentation

If the link identifier is not specified, the last link opened by mysql_connect() is assumed.



来源:https://stackoverflow.com/questions/138565/php-class-database-connection-scope-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!