PHP类数据库连接范围问题

问题描述:

对于我正在使用PHP进行的新项目,我创建了一个SQLMethods类以连接到数据库并执行查询。今晚是我实际上要进行测试的第一天(大约一个星期前我写了它,却忘了它),并发生了意外错误:当它调用ExecuteQuery()函数时,它将不会使用数据库

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.

构造函数:

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

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

        mysql_select_db($SQLDB, $SQLConnection);
    }

相关函数:

    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?

您应在类中声明$ SQLConnection,并将其引用为:

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

 $this->SQLConnection

而不仅仅是$ SQLConnection。

and not simply $SQLConnection.