note 118034 added to mysqli.ping
| From: | root at jusme dot org | Date: | Mon, 21 Sep 2015 22:00:14 +0000 |
| Subject: | note 118034 added to mysqli.ping | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-203833@lists.php.net to get a copy of this message | ||
As jay at grooveshark dot com very helpfully pointed out, the mysqlnd driver which is becoming
pretty standard does not obey reconnect commands. If you have a DB wrapper class (which hopefully
you do) you can implement your own version of ping() such as:
<?php
class db extends mysqli
{
private $db_host;
private $db_user;
private $db_pass;
private $db_name;
private $persistent;
public function __construct($db_host, $db_user, $db_pass, $db_name, $persistent = true)
{
$this->db_host = $db_host;
$this->db_user = $db_user;
$this->db_pass = $db_pass;
$this->db_name = $db_name;
$this->persistent = $persistent;
parent::init();
parent::options(MYSQLI_OPT_CONNECT_TIMEOUT, 1);
@parent::real_connect(($this->persistent ? 'p:' : '') .
$this->db_host, $this->db_user, $this->db_pass, $this->db_name);
if ($this->connect_errno)
die("All DB servers down!\n");
}
public function ping()
{
@parent::query('SELECT LAST_INSERT_ID()');
if ($this->errno == 2006)
$this->__construct($this->db_host, $this->db_user, $this->db_pass,
$this->db_name, $this->persistent);
}
...
}
$db = new db(DB_HOST, DB_USER, DB_PASS, DB_NAME);
// Some code that potentially takes a really long time to execute goes here
// Ping for safety to try to gracefully reconnect
$db->ping();
// Now we should be able to run queries again
$db->query('SELECT LAST_INSERT_ID()');
?>
If you wanted you could even put "$this->ping();" at the top of db::query() to avoid
any explicit reconnection calls but I wouldn't recommend it due to the (slight) overhead of
running the cheap "SELECT LAST_INSERT_ID()" query every time prior to running your real
intended query. There are probably even cheaper queries to run in favor of "SELECT
LAST_INSERT_ID()" but it was the first that came to mind and is cheap enough for most purposes
since you shouldn't be calling ping() a whole bunch anyway.
----
Server IP: 72.52.91.14
Probable Submitter: 50.135.189.87
----
Manual Page -- http://php.net/manual/en/mysqli.ping.php
Edit -- https://master.php.net/note/edit/118034
Del: integrated -- https://master.php.net/note/delete/118034/integrated
Del: useless -- https://master.php.net/note/delete/118034/useless
Del: bad code -- https://master.php.net/note/delete/118034/bad+code
Del: spam -- https://master.php.net/note/delete/118034/spam
Del: non-english -- https://master.php.net/note/delete/118034/non-english
Del: in docs -- https://master.php.net/note/delete/118034/in+docs
Del: other reasons-- https://master.php.net/note/delete/118034
Reject -- https://master.php.net/note/reject/118034
Search -- https://master.php.net/manage/user-notes.php