What are the possible results of PDO :: getAttribute (PDO :: ATTR_CONNECTION_STATUS)

I have been doing this for most of the day .. and can't seem to find the values โ€‹โ€‹returned anywhere. Can someone tell me:

  • What values โ€‹โ€‹return PDO::getAttribute(PDO::ATTR_CONNECTION_STATUS); ?
  • Can one rely on its result to determine if the compound is still alive? (And in the end, what can I use to check if the connection is alive?)
+7
source share
1 answer

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) } // some methods public function isConnected() { try { return (bool) $this->link->query('SELECT 1+1'); } catch (PDOException $e) { return false; } } //some other methods } 

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.

+3
source

All Articles