At last! it turns out that the mysqli::ping() function can be implemented in 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) }
CAUSE:
PDO::query(); returns an array containing the results or false, in the current case it will not return anything, because the connection is dead, and PDO should throw an exception from us. And that is what we expect. The catch block will return false and will not stop the execution of our script. Query used
SELECT 1 + 1;
will always return 2, and it is good to rely on the fact that it is calculated on the side of the database. No connection, no result! This is not overkill because it is a very simple query and most of the databases (on a regular shared host) are on the local host and it will not take more than 0.0000s , which is not so much related to performance. Not yet tested it with transactions, but should do the trick.
DaGhostman Dimitrov
source share