我正在使用XAMPP,我想检测MySQL数据库是否正在运行。我的代码如下所示:
$this->connection = mysqli_connect(
$this->host,
$this->name,
$this->pass,
$this->db
);
if ($this->connection->connect_errno)
{
$this->connection = false;
return false;
} else { $this->connection->set_charset('utf-8'); }
我收到以下日志:
PHP警告:mysqli_connect():( HY000 / 2002):连接被拒绝...
PHP注意:尝试获取//中的非对象属性//这是指$ this-> connection-> connect_errno
PHP致命错误:在布尔值
上调用成员函数set_charset()
我该怎样防止这种情况?如何检查数据库是否可用?
答案 0 :(得分:3)
首先,您要禁用警告报告或禁止mysqli_connect
来电,或将其嵌入try/catch
区块。
然后,不是先检查connect_errno
,而是首先验证connection
是否为真值。像这样
$this->connection = false;
try {
$this->connection = mysqli_connect(
$this->host,
$this->name,
$this->pass,
$this->db
);
if (!$this->connection || $this->connection->connect_errno)
{
$this->connection = false;
return false;
} else {
$this->connection->set_charset('utf-8');
}
} catch ($e) { //something bad happened. Probably not recoverable.
$this->connection = false;
return false;
}
答案 1 :(得分:3)
我不是这个答案的作者,它只是另一篇文章的原始版本,这是给出条件的唯一正确解决方案
首先,您需要停用警告报告或禁止mysqli_connect
来电。
然后,不要先检查connect_errno
,而是先验证connection
是否为真值。像这样
$this->connection = @mysqli_connect( //<-- warnings suppressed
$this->host,
$this->name,
$this->pass,
$this->db
);
if (!$this->connection || $this->connection->connect_errno) //lazy evaluation will prevent any issues here
{
$this->connection = false;
return false;
} else { $this->connection->set_charset('utf-8'); }