What are the possible results of PDO::getAttribute(PDO::ATTR
I have been looking in to this almost all day.. and can't seem to find the values returned anywhere. Can somebody tell me:
PDO::getAttribute(PDO::ATTR_CONNECTION_STATUS);
return? Finally! it turns out that the mysqli::ping()
function could be implemented within PDO as follows:
class PDOExtended extends PDO {
public function __construct($dsn, $user, $pass, $options = array())
{
$this->link = parent::__construct($dsn, $user, $pass, $options);
$this->link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)
}
// some methods
public function isConnected()
{
try {
return (bool) $this->link->query('SELECT 1+1');
} catch (PDOException $e) {
return false;
}
}
//some other methods
}
REASON:
PDO::query();
returns array containing the results or false, In the current case it won't return nothing, cuz the connection is dead and PDO should throw an exception at us. And that is what we are expecting. The catch block will return false and and will not stop the execution of our script. The query used
SELECT 1+1;
will return 2 always and it is good to rely on due to the fact that it is calculated on the DB side. No connection, no result! It is not an overkill because it is very simple query and most of the databases (on normal shared host) are on localhost it will not take more than 0.0000s
which is not much of a performance issue. Have not tested it with transactions yet, but should do the trick still.