为什么要显示多个数据库连接?

时间:2016-12-18 14:23:17

标签: php mysqli connection

elow是我网站的一些文件结构。我从这些示例代码中删除了不必要的代码,以避免混淆和更大的代码块。

class:connection.php(从互联网上收集)

<?php
class connection {
    private $_connection;
    private static $_instance; //The single instance
    private $_host = "localhost";
    private $_username = "username";
    private $_password = "password";
    private $_database = "database";

    /*
    Get an instance of the Database
    @return Instance
    */
    public static function getInstance() {
        if(!self::$_instance) { // If no instance then make one
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    // Constructor
    private function __construct() {
        $this->_connection = new mysqli($this->_host, $this->_username,
            $this->_password, $this->_database);
        }

    // Magic method clone is empty to prevent duplication of connection
    private function __clone() { }

    // Get mysqli connection
    public function getConnection() {
        return $this->_connection;
    }
}
?>

class:login.php(此类授权网站中的用户)

class login extends connection{
private $conn;
private $userid;
public $loggedin;

function __construct($id){
    $this->userid = $id;
    $this->set_login();
}

private function set_login(){
    $this->connect();
    $result = $this->conn->query("SELECT status FROM users WHERE userid='".$this->userid.'"');
    if($result){
       $this->loggedin = true;
    }else{
       $this->loggedin = false;
    }
}

private function connect(){
    $this->conn = parent::getInstance()->getConnection();
}
}

phppage:index.php(此页面用于测试连接数)

<?php
spl_autoload_register(function ($class) {
    include '../classes/' . $class . '.php';
});
$user = new login("75");
if($user->logged_in){
    $db = connection::getInstance();
    $conn = $db->getConnection();
    $query = 'SHOW STATUS WHERE variable_name LIKE "Threads_%" OR variable_name = "Connections"';
    $result = $conn->query($query);
    while($row=$result->fetch_assoc()){
      echo $row['Variable_name'].'  -  '.$row['Value'].'<br />';
    }
}
?>

index.php将显示有关连接的以下信息:

Connections - 1026572
Threads_cached - 7
Threads_connected - 9
Threads_created - 42943
Threads_running - 2

我在上面的示例中引用了两个$conn,一个在login.php类中,另一个在index.php页面中,但来自同一个connection.php类。

我可以知道Threads_running值的总有效连接数。但有时我可以在重新加载页面时看到Threads_running - 2,有时会变成Threads_running - 1

所以,我向专家提出的问题是,根据上面的类,是否有可能同时拥有多个数据库连接?

如果不是,为什么它有时显示Threads_running - 2,这意味着一次有多个连接?

0 个答案:

没有答案