How to check if there is an active MySQLi connecti

2019-06-09 13:37发布

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.

标签: php oop mysqli
3条回答
放荡不羁爱自由
2楼-- · 2019-06-09 14:37

Try this one:

parent::__construct("p:".$host, MySQL_USER, MySQL_PASS, MySQL_DATABASE);
查看更多
手持菜刀,她持情操
3楼-- · 2019-06-09 14:41
  • 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!\n");
} else {
    printf ("Error: %s\n", $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.

查看更多
孤傲高冷的网名
4楼-- · 2019-06-09 14:42

When connecting to the database you can put p: before the hostname to initiate a persistent connection. Like, p:mysite.com or p:localhost. This may help with speed (if you are not already doing it)

查看更多
登录 后发表回答