1
votes

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:

Warning: PDO::__construct(): MySQL server has gone away in /path/to/website/mysql.inc.php on line 3

2
That looks to be a warning not an error. The first connection is going away, so it throws the warning. Is the connection still persistent after the second connection? - Shawn
@shawn how can I make it into an error? - john01dav
By default PDO throws a warning. Set PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION. I believe that will throw an exception instead. If it works for you ill make this an official answer. - Shawn
John did this work for you? - Shawn

2 Answers

4
votes

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());
    }
}
0
votes

the @ operator suppresses the warning:

$db = @new PDO(...