【问题标题】:How do I detect whether a MySQL database is running or not?如何检测 MySQL 数据库是否正在运行?
【发布时间】:2015-10-15 17:32:58
【问题描述】:

我正在使用 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): Connection denied ...

PHP 注意:试图获取非对象的属性 // this 指的是 $this->connection->connect_errno

PHP 致命错误:在布尔值上调用成员函数 set_charset()

如何防止这种情况发生?如何检查一般数据库是否可用?

【问题讨论】:

  • try / catch 语句中执行您的连接,以便您可以优雅地处理错误。
  • 你能展示全班吗?

标签: php mysql mysqli


【解决方案1】:

首先,您需要为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;
}

【讨论】:

  • 永远不要抑制警告,这是一个糟糕的计划。
  • 我会将连接放在try / catch 中,以便更恰当地处理错误。
  • 啊,我不知道警告实际上可以正确捕获。谢谢你的提示。我改进了我的答案。
  • 这是您的答案,您可以根据需要对其进行编辑(只要您不破坏它)。如果这导致回滚战争,请标记以获得 mod 帮助。
  • 关于此答案编辑的元帖子:meta.stackoverflow.com/questions/308122 (cc @YourCommonSense)
【解决方案2】:

我不是这个答案的作者,它只是另一个帖子的原始版本,这是给定条件的唯一正确解决方案

首先,您需要为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'); }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多