PHP PDO implements a method to determine if a connection is available

Source: Internet
Author: User
Tags dsn pconnect php cli
This article mainly introduces the PHP PDO to determine whether the connection is available, interested in the friend's reference, I hope to be helpful to everyone.

Mysql_ping () checks to see if the connection to the server is healthy. Returns true if the connection to the server is available, otherwise false.

However, PDO does not support the mysql_ping () method, so you need to write your own code to simulate the Mysql_ping () method to check if the connection is available.

The code is as follows:

<?php/** * Check if the connection is available * @param link $dbconn database connection * @return Boolean */function pdo_ping ($dbconn) {  try{    $dbconn-&G T;getattribute (Pdo::attr_server_info);  } catch (Pdoexception $e) {    if (Strpos ($e->getmessage (), ' MySQL server has gone away ')!==false) {      return false;< c9/>}  }  return true;}? >

Code Demo:

1. Create test Data Sheet

CREATE TABLE ' user ' (' id ' int (one) unsigned not null auto_increment, ' name ' varchar (a) NOT NULL, PRIMARY KEY (' id ')) ENGI Ne=innodb DEFAULT Charset=utf8;


2. Inserting test data

Insert into user (name) values (' Fdipzone '), (' Xfdipzone '), (' Terry ');mysql> select * from user;+----+-----------+| ID | Name   |+----+-----------+| 1 | fdipzone | | 2 | xfdipzone | | 3 | Terry   |+----+-----------+


3. Presentation files

db.php

<?php//database Operation class db{//Save database connection private static $_instance = null;      Connect database public static function Get_conn ($config) {if (Isset (self::$_instance) &&!empty (self::$_instance)) {    return self::$_instance;    } $dbhost = $config [' Host '];    $dbname = $config [' dbname '];    $dbuser = $config [' user '];    $DBPASSWD = $config [' Password '];    $pconnect = $config [' Pconnect '];    $charset = $config [' CharSet '];    $DSN = "mysql:host= $dbhost;d bname= $dbname;";      try {$h _param = array (Pdo::attr_errmode = Pdo::errmode_exception,); if ($charset! = ") {$h _param[pdo::mysql_attr_init_command] = ' SET NAMES '. $charset;//setup default encoding} if ($p      Connect) {$h _param[pdo::attr_persistent] = true;    } $conn = new PDO ($DSN, $dbuser, $dbpasswd, $h _param); } catch (Pdoexception $e) {throw new errorexception (' Unable to connect to DB server. Error: '.    $e->getmessage (), 31);    } self::$_instance = $conn; Return $conN    }//Execute query public static function query ($dbconn, $SQLSTR, $condparam) {$sth = $dbconn->prepare ($SQLSTR);    try{$sth->execute ($condparam); } catch (Pdoexception $e) {echo $e->getmessage ().    Php_eol;    } $result = $sth->fetchall (PDO::FETCH_ASSOC);  return $result;  }//Reset connection public static function Reset_connect () {self::$_instance = null; }}?>

test.php

<?phprequire ' db.php ';//Database Settings $config = array (' host ' = ' localhost ', ' dbname ' = ' user ', ' user ' = ' root ', ' Password ' = ' = ', ' pconnect ' = 0, ' charset ' + ');//Loop execution while (true) {//create data connection $dbconn = Db::get_conn ($c  Onfig);  Determine if the connection is valid $status = Pdo_ping ($dbconn); if ($status) {echo ' Connect ok '.  Php_eol; }else{echo ' Connect failure '.    Php_eol;    Reset Connection Db::reset_connect ();  $dbconn = Db::get_conn ($config);  }//Execute Query $sqlstr = ' SELECT * from user where id=? ';  $condparam = Array (Mt_rand (1,3));  $data = Db::query ($dbconn, $sqlstr, $condparam);  Print_r ($data); 10 seconds delay echo ' sleep 10 '. Php_eol.  Php_eol; Sleep (10);} /** * Check if the connection is available * @param link $dbconn database connection * @return Boolean */function pdo_ping ($dbconn) {try{$dbconn->getattribu  Te (Pdo::attr_server_info);    } catch (Pdoexception $e) {if (Strpos ($e->getmessage (), ' MySQL server has gone away ')!==false) {return false; }} return true;}? >

4. Implementation

Execute test.php in PHP CLI mode and execute Mysql.server stop and mysql.server start analog flash

Mysql.server stopshutting down MySQL .... success! Mysql.server startstarting MySQL success!


Execution output:

Connect Okarray (  [0] = = Array    (      [id] = 2      [name] = Xfdipzone    )) Sleep 10connect Failurearray (  [0] = = Array    (      [id] = 3      [name] = Terry    )) Sleep 10connect Okarray (  [0] = = Array    (      [id] = 3      [name] = Terry    )) Sleep 10

You can see the Flash, Pdo_ping () returns false, the connection fails, and then the automatic reconnection is called to ensure that subsequent queries continue to execute.

The above is the whole content of this article, I hope that everyone's study has helped.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.