Handle PHP reconnect

Handle PHP reconnect when getting the 2006 error code from MySQL


<?php

class reconnectPDO extends PDO
{
 var $connection_array = [];
 var $reconnect_limit = 5;
 var $reconnect_time = 1;
 var $reconnect_counter = 0;

 public function __construct($dsn, $username, $passwd, $options)
 {
  $this->connection_array = [
   'd' => $dsn,
   'u' => $username,
   'p' => $passwd,
   'o' => $options
  ];
  $this->connect();
 }

 public function connect()
 {
  echo "connecting\n";
  $c =& $this->connection_array;
  parent::__construct($c['d'], $c['u'], $c['p'], $c['o']);
  try
  {
   $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('reconnectPDOStatement', array($this)));
   $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  }
  catch (PDOException $e)
  {
   die($e->getMessage());
  }
 }

 public function run_reconnect($function, $param)
 {
  echo "run_reconnect {$this->reconnect_counter}\n";
  $return = false;
  do
  {
   $reconnect = false;
   try
   {
    $return = parent::$function($param);
   }
   catch (Exception $e)
   {
    if ($e->getCode() == 2006)
    {
     $this->reconnect_counter++;
     if ($this->reconnect_counter < $this->reconnect_limit)
     {
      sleep($this->reconnect_time);
      $reconnect = true;
     }
    }
   }
  } while ($reconnect == true);

  return $return;
 }

 public function query($query, $reconnect = true)
 {
  if ($reconnect)
  {
   $result = $this->run_reconnect('query', $query);
  }
  else
  {
   $result = parent::query($query);
  }

  return ($result);
 }

 public function exec($query, $reconnect = true)
 {
  if ($reconnect)
  {
   $result = $this->run_reconnect('exec', $query);
  }
  else
  {
   $result = parent::exec($query);
  }

  return ($result);
 }

 #get the number of rows in a result
 public function num_rows($query)
 {
  $stmt = parent::prepare($query);
  if ($stmt)
  {
   $stmt->execute();

   return $stmt->rowCount();
  }
  return false;
 }
}

class reconnectPDOStatement extends PDOStatement
{
 public $dbh;

 protected function __construct($dbh)
 {
  $this->dbh = $dbh;
 }
}

Popular Posts