I am attempting to make a php + pdo website that has persistent connections. Of course, the connections are closed every 8 hours of inactivity so I am attempting to create a php file that reopens the connection if it is closed
Here is my code:
try{
$db = new PDO("mysql:host=$database_ip;dbname=$database_name", $database_username, $database_password, array(PDO::ATTR_PERSISTENT => true));
}catch(Exception $x){
try{
$db = new PDO("mysql:host=$database_ip;dbname=$database_name", $database_username, $database_password);
}catch(Exception $x){
echo 'Failed database error';
}
}
This says that "PDO::__construct() will always throw a PDOException if the connection fails regardless of which PDO::ATTR_ERRMODE is currently set. Uncaught Exceptions are fatal."
The problem is that even though the exception is caught it is still fatal :/
Here's the error:
: PDO::__construct(): MySQL server has gone away in on line :PDO :: __ construct():第行上的 ,MySQL服务器已消失
First of all you should catch PDOException
Second you are already trying to reconnect so set ATTR_PERSISTENT
to FALSE
.
try{
$db = new PDO( '...' ); // array(PDO::ATTR_PERSISTENT => FALSE)
}catch(PDOException $x){
echo 'Caught exception: ', $x->getMessage(), "\n";
try{
//reconnect
$db = new PDO( '...' );
}catch(PDOException $e){
throw new Exception('Failed database error'.$e->getMessage());
}
}
@运算符禁止显示警告:
$db = @new PDO(...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.