如何检查PHP中是否存在活动的MySQLi连接? [英] How to check if there is an active MySQLi connection in PHP?

查看:95
本文介绍了如何检查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.

              这篇关于如何检查PHP中是否存在活动的MySQLi连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆