PHP连接MySQL时, 有可能因为MySQL的原因,而使得php里生成的连接无效。比如超过8小时, MySQL自动断开空闲连接的问题,虽然可以调高这个时间,但显然这不是比较文艺的实现方式。现在洒家用PHP检测连接是否有效的方法,然后再重新连接无效的连接,这样就比较智能化了。
直接上代码:
<?php /* define('MYSQL_HOST','192.168.0.1'); define('MYSQL_USER','root'); define('MYSQL_PASSWD','123'); define('MYSQL_PORT','3306'); define('MYSQL_DBNAME','mysql'); define('MYSQL_CHARSET','utf8'); */ /** * PDOMySQL实现类, 自动重置无效连接 * @author 1125271180@qq.com lcs */ class PDOMySQL { private $conn; function __construct(){ $this->connect(); } function connect(){ $cnt = 1; // 在3*10秒内尝试连接10次 while(!$this->conn){ try{ $this->conn = new PDO("mysql:dbname=".MYSQL_DBNAME.";host=".MYSQL_HOST, MYSQL_USER, MYSQL_PASSWD); // 错误报告,抛出 exceptions 异常。这里要设置,要不然ping函数不起作用 $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); }catch(PDOException $e){ echo date('Y-m-d H:i:s')." PDOMySQL::connect PDOException ".$e->getMessage()." "; $this->conn = null; } sleep(3); if ($cnt++ > 10){ break; } } return $this->conn; } public function query($sql){ $mixed = array(); $rest = null; try{
$this->conn = $this->resetConnection();
if ( !$this->conn){
echo date('Y-m-d H:i:s')." PDOMySQL::query PDO_MYSQL connection is lost. "." ";
return $mixed;
} $rest = $this->conn->query($sql, PDO::FETCH_ASSOC); } catch (PDOException $e) { echo date('Y-m-d H:i:s')." PDOMySQL::query PDOException ".$e->getMessage()." "; $rest = null; } if ( $rest ) { foreach($rest as $row){ $mixed[] = $row; } } return $mixed; } /** * 重置连接 */ function resetConnection(){ // echo "resetConnection "." "; $res = $this->ping(); if (!$res){ $this->conn = $this->connect(); } return $this->conn; } /** *检查connection是否有效 */ function ping(){ if ($this->conn) { try{ $res = $this->conn->getAttribute(PDO::ATTR_SERVER_INFO); // echo $res." "; } catch (PDOException $e) { echo date('Y-m-d H:i:s')." PDOMySQL::ping PDOException ".$e->getMessage()." "; if(strpos($e->getMessage(), 'server has gone away')!==false){ $this->conn = null; return false; } } return true; }else{ echo date('Y-m-d H:i:s')." PDOMySQL::ping PDO_MYSQL connection is lost. "." "; } return false; } } // ...