dongyan8896 2014-02-10 11:38
浏览 92
已采纳

如何检查PHP中是否存在活动的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.

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

My Database class looks like this :

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...     
}

A sample model class would look like this :

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.
    }                
}

My question is,

  • How can i check if there is an active mysqli connection?

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

  • What other approaches can i follow?

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

P.S.: Migrating to PDO will be a lot of rework, as i've already built things over mysqli.

  • 写回答

3条回答 默认 最新

  • dongxu4023 2014-02-24 10:42
    关注
    • How can i check if there is an active mysqli connection?

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

    This is from php.net :

    if ($mysqli->ping()) {
        printf ("Our connection is ok!
    ");
    } else {
        printf ("Error: %s
    ", $mysqli->error);
    }
    
    • How can i prevent it from reconnecting and use the active connection instead?

    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?

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了