MySQL服务器消失后重新连接到mysql错误

时间:2018-07-27 22:28:35

标签: php mysql mysqli

下面的

是使用单例的数据库类。我不确定我的checkDBconnnection方法。当我遇到MySQL server has gone away错误并通过在$this->getInstance();中调用checkDBconnnection()来检查是否重新连接时,我一直在循环中遇到MySQL server has gone away错误。任何帮助将不胜感激。谢谢

class DB {

    private $_mysqli, 
            $_query, 
            $_results = [], 
            $_count = 0;

    public static $instance;


    public static function getInstance(){

        if(!isset(self::$instance)){
            self::$instance = new DB();
        }
        return self::$instance;
    }

    public function  __construct() {

        $details = $this->mysqlUrl();
        $this->_mysqli =  new mysqli($details['host'], $details['user'], $details['pass'], $details['database']);
        if ($this->_mysqli->connect_error) {
            throw new expection("Connection failed: " . $this->_mysqli->connect_error);
        } 
    } 



    public function query($query){
        $this->checkDBconnnection();
        if($this->_query = $this->_mysqli->query($query)){
            if ($this->_query->num_rows > 1) {
                while($row = $this->_query->fetch_assoc()) {
                    $data[] = $row;
                }
            }

            if ($this->_query->num_rows <= 1) {
                $data[0] = $this->_query->fetch_assoc();
            }

            return $data;
        }
    }


    public function checkDBconnnection(){

        $state = false;
        log_message("checkDBconnnection", "Checking mysqli connection", "");
        while ($state == false){

            if ($this->_mysqli->ping()) {
                $state = true;
                log_message("checkDBconnnection", "mysqli state", $state);
            } else {

                sleep(30);
                $state = false;
                log_message("checkDBconnnection", "mysqli state", $this->_mysqli->error);
                log_message("checkDBconnnection", "Reconnecting to database", "");
                $this->getInstance();

            }
        }

    }
}

0 个答案:

没有答案