php数据库备份还原类分享(2)

/**
  * 写入文件
  * @param array $tables
  * @param array $ddl
  * @param array $data
  */
 private function writeToFile($tables = array(), $ddl = array(), $data = array())
 {
  $str = "/*\r\nMySQL Database Backup Tools\r\n";
  $str .= "Server:{$this->config['host']}:{$this->config['port']}\r\n";
  $str .= "Database:{$this->config['database']}\r\n";
  $str .= "Data:" . date('Y-m-d H:i:s', time()) . "\r\n*/\r\n";
  $str .= "SET FOREIGN_KEY_CHECKS=0;\r\n";
  $i = 0;
  foreach ($tables as $table)
  {
   $str .= "-- ----------------------------\r\n";
   $str .= "-- Table structure for {$table}\r\n";
   $str .= "-- ----------------------------\r\n";
   $str .= "DROP TABLE IF EXISTS `{$table}`;\r\n";
   $str .= $ddl[$i] . "\r\n";
   $str .= "-- ----------------------------\r\n";
   $str .= "-- Records of {$table}\r\n";
   $str .= "-- ----------------------------\r\n";
   $str .= $data[$i] . "\r\n";
   $i++;
  }
  echo file_put_contents($this->config['target'], $str) ? '备份成功!花费时间' . (microtime(true) - $this->begin) . 'ms' : '备份失败!';
 }

/**
  * 错误信息
  * @return mixed
  */
 public function getError()
 {
  return $this->error;
 }

public function restore($path = '')
 {
  if (!file_exists($path))
  {
   $this->error('SQL文件不存在!');
   return false;
  }
  else
  {
   $sql = $this->parseSQL($path);
   try
   {
    $this->handler->exec($sql);
    echo '还原成功!花费时间', (microtime(true) - $this->begin) . 'ms';
   }
   catch (PDOException $e)
   {
    $this->error = $e->getMessage();
    return false;
   }
  }
 }

/**
  * 解析SQL文件为SQL语句数组
  * @param string $path
  * @return array|mixed|string
  */
 private function parseSQL($path = '')
 {
  $sql = file_get_contents($path);
  $sql = explode("\r\n", $sql);
  //先消除--注释
  $sql = array_filter($sql, function ($data)
  {
   if (empty($data) || preg_match('/^--.*/', $data))
   {
    return false;
   }
   else
   {
    return true;
   }
  });
  $sql = implode('', $sql);
  //删除/**/注释
  $sql = preg_replace('/\/\*.*\*\//', '', $sql);
  return $sql;
 }
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/dd00f6447550d42730cb15e463bee4fe.html