如何在PHP中启用数据库自动重新连接? [英] how to enable database auto-reconnect in PHP?
本文介绍了如何在PHP中启用数据库自动重新连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
并且数据库是MYSQL
and the database is MYSQL
推荐答案
有时,当您的MySQL连接打开时间过长时,如果没有查询的时间超过my.cnf中的wait_timeout值,则将断开与数据库的连接.您将收到"MySQL服务器已消失"超时错误.
Sometimes when your MySQL connection opened for too long, the connection to the DB will be dropped when the time without a query exceeds the wait_timeout value in my.cnf. You will get "MySQL server has gone away" timeout error.
这是我在代码中实现自动重新连接的方式:
This is how I implement auto reconnect in my code:
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);
}
}
有关此处的更多信息,请参考 mysql_ping
Refer here for more infomation about mysql_ping
这篇关于如何在PHP中启用数据库自动重新连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文