Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i ping the MySQL db and reconnect using PDO

Tags:

php

mysql

pdo

I am using MySQL PDO for handling database querying and all. But most of the time, the MySQL connection is gone away. So i am looking in the PDO that will check if the db connection is exists or not and if it is not exit, then i need to connect the database to continue the query execution.

I am new to the MySQL pdo and i do not know how to handling this situation. It would be better if anybody suggest on this.

like image 201
Raja Avatar asked Apr 23 '14 12:04

Raja


People also ask

Does PDO work with MySQL?

PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL databases. So, if you have to switch your project to use another database, PDO makes the process easy. You only have to change the connection string and a few queries.

How do I know if my MySQL database is connected?

To test the connection to your database, run the telnet hostname port on your Looker server. For example, if you are running MySQL on the default port and your database name is mydb, the command would be telnet mydb 3306 . If the connection is working, you will see something similar to this: Trying 10.10.


1 Answers

I tried to find a solution for the same problem and I found the next answer:

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);
    }
}

Full story here: https://terenceyim.wordpress.com/2009/01/09/adding-ping-function-to-pdo/


Somebody else was thinking to use PDO::ATTR_CONNECTION_STATUS, but he figured out that: "$db->getAttribute(PDO::ATTR_CONNECTION_STATUS) keeps replying “Localhost via UNIX socket” even after stopping mysqld".

like image 134
Cristian Ciocău Avatar answered Oct 16 '22 03:10

Cristian Ciocău