Programming collection

January 9, 2009

Adding ping() function to PDO

Filed under: PHP, programming — terenceyim @ 4:36 pm

Recently helped my colleague to add the missing mysqli_ping() function to PDO object in PHP. If anyone missed it, here it is:

<?php
class NPDO {
    private $pdo;
    private $params;

    public function __construct() {
        $this->params = func_get_args();
        $this->init();
    }

    public function __call($name, array $args) {
        return call_user_func_array(array($this->pdo, $name), $args);
    }

    // The ping() will try to reconnect once if connection lost.
    public function ping() {
        try {
            $this->pdo->query('SELECT 1');
        } catch (PDOException $e) {
            $this->init();  // Don't catch exception here, so that re-connect fail will throw exception
        }

        return true;
    }

    private function init() {
        $class = new ReflectionClass('PDO');
        $this->pdo = $class->newInstanceArgs($this->params);
    }
}
?>

4 Comments »

  1. Just passing by.Btw, you website have great content!

    _________________________________
    Making Money $150 An Hour

    Comment by Mike — March 1, 2009 @ 1:46 am | Reply

  2. thx man!

    Comment by xrado — March 20, 2009 @ 6:47 am | Reply

  3. have you tried PDO::ATTR_CONNECTION_STATUS ?

    Comment by Samus_ — March 27, 2009 @ 2:13 pm | Reply

  4. meh nevermind, $db->getAttribute(PDO::ATTR_CONNECTION_STATUS) keeps replying “Localhost via UNIX socket” even after stopping mysqld :P

    Comment by Samus_ — March 27, 2009 @ 2:25 pm | Reply


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.