How to ping the mysql server in Yii2 Framework

658 views Asked by At

I am looking to be able to ping the MySQL server using mysql_ping() (mysqli_ping()) inside the Yii2 Framework.

I currently use the createCommand() for all my SQL queries so I do not have a good understanding of how to use the ping function outside of that scope.

I am not sure how to even grab the SQL link inside go Yii.

I do not have any test code since I am not even sure where to start.

Any help to point me in the right direction will be appreciated.

1

There are 1 answers

2
rob006 On

Yii DB component uses PDO, which does not have mysql_ping() equivalent. The closest what you can get is to query SELECT 1 and reconnect if exception occurred.

public function ping() {
    try {
        Yii::$app->db->createCommand('SELECT 1')->query();
    } catch (\yii\db\Exception $exception) {
        Yii::$app->db->close();
        Yii::$app->db->open();
    }
}

Note that reconnection implicitly may result unexpected and silent rollbacks if you're using transactions.