如何检查PHP中是否存在活动的MySQLi连接?

问题描述:

我已经从mysqli类扩展了数据库模型,但是我不希望每次实例化一个新模型时都重新连接它,因为这确实降低了整个脚本的速度.

I have extended my Database Models from the mysqli class, but i don't want it to reconnect everytime i instantiate a new model, because it really slows down the whole script.

我有一个Database类从mysqli扩展而来,其他 model类Database扩展.

I have a Database class extends from mysqli, and other model classes extending from Database.

我的Database类如下所示:

class Database extends mysqli {

    // some properties ...

    public function __construct() {
        parent::__construct(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DATABASE);
        $this->set_charset(MySQL_CHARACTER_SET);

        // initializing stuff ..             
    }

    // some other methods...     
}

示例模型类如下所示:

class User extends Database {
    protected $table = "users";

public function __construct($id = null) {
    // Calling the parent constructor.
    parent::__construct();
    if($id) {
        // This is the current logged-in user.
        // Importing all session data into this object.
        $this->data->import($this->session->all());
        // ^^ This imports all the user related session data into this object 
        // i don't think it's relevant but i'll leave it here just in case.
    }                
}

我的问题是

  • 我如何检查是否存在有效的mysqli连接?

如何防止其重新连接并改为使用活动连接?

How can i prevent it from reconnecting and use the active connection instead?

我还可以采用哪些其他方法?

What other approaches can i follow?

我是否必须迁移到PDO? 为什么?

Should i migrate to PDO, do i have to? Why?

P.S .:迁移到PDO将需要大量的工作,因为我已经通过mysqli构建了这些东西.

  • 我如何检查是否存在活动 mysqli 连接?
    • How can i check if there is an active mysqli connection?
    • 您可以使用mysqli::ping()方法检查连接是否处于活动状态.

      You can use mysqli::ping() method to check if the connection is alive.

      这来自 php.net :

if ($mysqli->ping()) {
    printf ("Our connection is ok!\n");
} else {
    printf ("Error: %s\n", $mysqli->error);
}

  • 如何防止其重新连接并改用活动连接?
    • How can i prevent it from reconnecting and use the active connection instead?
    • 正如其他答案所述,使用持久连接将解决您的问题.在主机名中添加p:前缀.

      As the other answers say, using a persistent connection will solve your problem. Add p: prefix to your host name.

parent::__construct("p:" . MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DATABASE);

  • 我还可以采用哪些其他方法?
    • What other approaches can i follow?
    • 您可以考虑使用PDO,但是如果您不需要支持其他数据库类型,或者准备好的语句mysqli对我来说看起来更轻便.

      You could consider using PDO instead, but if you don't need to support other DB types, or prepared statements mysqli looks more lightweight to me.