PHP 类数据库连接范围问题
对于我用 PHP 做的新项目,我创建了一个 SQLMethods 类来连接到数据库并执行查询。 今晚是我真正测试它的第一个晚上(我大约一周前写的,然后忘记了),并且发生了意外错误:当它调用我的 ExecuteQuery() 函数时,它不会使用我的数据库在构造函数中选择。
构造函数:
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());
}
有人看到问题可能是什么吗? 构造函数完成后连接是否关闭?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该在您的类中声明 $SQLConnection,并且您应该将其称为
$SQLConnection 而不仅仅是 $SQLConnection。
you should declare $SQLConnection in your class, and you should refer to it as
and not simply $SQLConnection.
ExecuteQuery
方法中不存在$SQLConnection
。您可以将其作为参数直接传递给 ExecuteQuery,也可以添加一个在构造函数中设置的 sqlConnection 类属性,并通过
$this->sqlConnection 进行访问
在你的类方法中。$SQLConnection
doesn't exist within theExecuteQuery
method.You can either pass it directly as a parameter to
ExecuteQuery
, or add ansqlConnection
class property that is set in the constructor and accessed as$this->sqlConnection
inside your class methods.尝试使用的变量
$SQLConnection
ExecuteQuery()
是在另一个范围内创建的。 (SQLMethods
函数)。当 PHP 脚本完成其工作或您自己关闭连接(如果在该脚本内建立连接)时,连接将关闭
您应该跳过
ExecuteQuery
中的$SQLConnection
变量如 php.net 文档所述The variable
$SQLConnection
ExecuteQuery()
is trying to use is created within another scope. (TheSQLMethods
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 withinExecuteQuery
as stated by the php.net documentation