解决PHP脚本pdo MySQL has gone away错误 pdo加ping功能
<?php
class NPDO {
private $pdo;
private $params;
public function __construct() {
$this->params = func_get_args();
$this->init();
}
public function __call($name, array $args) {
try {
return call_user_func_array(array($this->pdo, $name), $args);
} catch (PDOException $e) {
}
}
public function ping() {
try {
$this->pdo->query('SELECT 1');
$error=$this->pdo->errorInfo();//由于pdo扩展的bug,有时不抛出异常,这里要加上错误信息
if ($error[2]=='MySQL server has gone away') {
$this->init();
}
} catch (PDOException $e) {
$this->init();
}
return true;
}
private function init() {
try {
$class = new ReflectionClass('PDO');
$this->pdo = $class->newInstanceArgs($this->params);
} catch (PDOException $e) {
}
}
}
$flysystempdo = new NPDO('mysql:dbname=test;host=localhost', 'root','root');
$flysystempdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
while (true) {
$flysystempdo->ping();
$sql = 'SELECT 1';
$aa=$flysystempdo->query($sql);
var_dump($aa);
sleep(1);
}
//另外2种
评论 (0)