MySQL server has gone away

class databaseClass {
    var $conn;
    var $db;

    public function __construct() {
        $this->connect();
    }

    public function connect() {
        $this->conn = mysql_connect(DB_HOST, DB_USER, DB_PASS);
        $this->db = mysql_select_db(DB_NAME, $this->conn);
    }

    public function disconnect() {
        mysql_close($this->conn);
    }

    public function reconnect() {
        $this->disconnect();
        $this->connect();
    }

    public function queryCompanyExist($company) {
        //auto reconnect if MySQL server has gone away
        if (!mysql_ping($this->conn)) $this->reconnect();

        $query =  "SELECT name FROM company WHERE name='$company'";
        $result = mysql_query($query);
        if (!$result) print mysql_error() . "\r\n";
        return mysql_fetch_assoc($result);
    }
}


mysqli reconnect=true


You can write a function which will ping the database via connection and in case it down, reconnect it again and then proceed the query or whatever you want, also take a look on mysqli php library, it can be useful for you.

PS. Also could be useful to implement Singleton design pattern in order to maintain the database connection, once created it will connect to database and then you can implement the method called getConnection which each time will proceed with the check I've described above.

PPS. You can use an exception, try you query, whenever it fails catch an exception, reconnect and try again.


你可能感兴趣的:(MySQL server has gone away)