PHP database backup Restore class sharing

Source: Internet
Author: User
Tags foreach getmessage mixed php database stmt table definition backup

  This article mainly introduces the PHP database backup and restore class, the need for friends can refer to the following

    Code as follows: <?php/**  * Database backup Restore class  * @author xialeistudio<admin@xialeistudio.net>  * S Databasetool  */class Databasetool { private $handler;  private $config = Array (  ' host ' => ' L Ocalhost ',   ' Port ' => 3306,   ' user ' => ' root ',   ' password ' => ',   ' database ' => ' test ',   ' charset ' => ' utf-8 ',   ' target ' => ' sql.sql '  );  private $tables = Array ();  private $error;  private $begin; Start time  /**   * Schema method   * @param array $config  / public function __construct ($config = Array () )  {  $this->begin = Microtime (true);   $config = Is_array ($config)? $config: Array ();   $this-& Gt;config = Array_merge ($this->config, $config);  /Start PDO connection   if (! $this->handler instanceof PDO)   {   try    {    $thi S->handler = new PDO ("mysql:host={$this->config[' host ']}:{$this->config[' port]};d bname={$this->config[' database '} ', $this->config[' user ', $this->config[' Password ']);   &nbsp    catch (pdoexception $e)    {    $this->error = $e->getmessage (); &n Bsp   return false;   &nbsp    catch (Exception $e)    {    $this->error = $e->getmessage (); &nbsp ;   return false;   &NBSP}  } &nbsp}    /**   * Backup   * @param array $tables   * @return BOOL   */  public function Backup ($tables = Array ())  { //Storage table Definition statement arrays   $DDL = array ();  //storing array of data &nbsp ; $data = Array ();   $this->settables ($tables);   if (!empty ($this->tables))   {   foreach ($this->tables as $table)    {  &nbs P $DDL [] = $this->getddl ($table);     $data [] = $this->getdata ($table);   &NBSP}    //starts writing     $this->writetofile ($thIs->tables, $DDL, $data);  }   Else   {    $this->error = ' no tables in database! ';    return false;  }  } &nbsp ;  /**   * Set the table to be backed up   * @param array $tables  / private function settables ($tables = Array ()) &NB Sp {  if (!empty ($tables) && Is_array ($tables))   {   //backup specified table     $this->tables = $ Tables  }   Else   {   //backup all tables     $this->tables = $this->gettables ();  }  }    /**   * Query   * @param string $sql   * @return mixed  / private function query ($s QL = ')  {  $stmt = $this->handler->query ($sql)   $stmt->setfetchmode (pdo::fetch_num);   $list = $stmt->fetchall ();   return $list; &NBSP}    /**   * Get all Tables   * @return array   */ private function gettables ()  {  $sql = ' show TABLES ';   $list = $this->query ($SQL);   $tables = array ();   foreach ($list as $value)   {    $tables [] = $value [0];  }   return $tables; &NBSP}    /**   * Get table definition statement   * @param string $table   * @return mixed  / private fun Ction getddl ($table = ')  {  $sql = "show CREATE table ' {$table} '";   $DDL = $this->query ($sql) [0][1] . ';';   return $DDL; &NBSP}    /**   * Get table Data   * @param string $table   * @return mixed  / private funct Ion GetData ($table = ')  {  $sql = "show COLUMNS from ' {$table} '";   $list = $this->query ($sql); &nbsp ; Fields   $columns = ';  //need to return SQL   $query = ';   foreach ($list as $value)   {    $columns. = "' {$value [0]} ', ';  }   $columns = substr ($co Lumns, 0,-1);   $data = $this->query ("select * from ' {$table} ')";   foreach ($data as $value)   {    $DATASQL = ';   &Nbsp;foreach ($value as $v)    {    $DATASQL. = "' {$v} ',";    }     $DATASQL = Sub STR ($DATASQL, 0,-1);     $query. = "INSERT into ' {$table} ' ({$columns}) VALUES ({$dataSql}); RN";  }   return $query; &NBSP}    /**   * Write file   * @param array $tables   * @param array $ddl   * @param array $dat A   *  private function writetofile ($tables = Array (), $ddl = Array (), $data = Array ())  {  $STR = " /*rnmysql Database Backup TOOLSRN ";   $STR. = "server:{$this->config[' host ']}:{$this->config[' Port ']}rn";   $STR. = "database:{$this->config[' Database ']}rn";   $STR. = "Data:". Date (' y-m-d h:i:s ', Time ()). "Rn*/rn";   $STR. = "SET Foreign_key_checks=0;rn";   $i = 0;   foreach ($tables as $table)   {    $str. = "------------------------------RN";     $STR. = "--Table structure for {$table}rn";     $STR. = "------------------------------RN ";     $STR. = "DROP TABLE IF EXISTS ' {$table} '; RN";     $STR. = $ddl [$i]. "RN";     $STR. = "------------------------------RN";     $STR. = "-Records of {$table}rn";     $STR. = "------------------------------RN";     $STR. = $data [$i]. "RN";     $i + +;  }   Echo file_put_contents ($this->config[' target '), $STR)? ' Backup successful! ' (Microtime (True)-$this->begin). ' MS ': ' Backup failed! ' &NBSP}    /**   * error message   * @return mixed   */ public function geterror ()  {  RE Turn $this->error; &NBSP}    public function restore ($path = ')  {  if (!file_exists ($path))   {    $th Is->error (' SQL file does not exist! ');    return false;  }   Else   {    $sql = $this->parsesql ($path);    try    {    $this->handler->exec ($sql);     echo ' restore success! Cost time ', (miCrotime (True)-$this->begin). ' MS ';   &nbsp    catch (pdoexception $e)    {    $this->error = $e->getmessage (); &n Bsp   return false;   &NBSP}  } &nbsp}    /**   * Parsing sql file as an array of SQL statements   * @param string $path   * @return AR ray|mixed|string  / private function parsesql ($path = ')  {  $sql = file_get_contents ($path); &nb Sp $sql = Explode ("rn", $sql);  //Elimination first-annotation   $sql = array_filter ($sql, function ($data)   {   if (empty ($data) | | preg_match ('/ ^--./*, $data))    {    return false;        else    {    return true;    }  });   $sql = Implode (", $sql);  //delete/**/annotation   $sql = preg_replace ('//*.**//', ', ', $sql);   return $sql; &NBSP}}  

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.