PHP database backup Restore class share _php tutorial

Source: Internet
Author: User
Tags getmessage php database table definition
Copy CodeThe code is as follows:
/**
* Database backup Restore class
* @author Xialeistudio
* Class Databasetool
*/
Class Databasetool
{
Private $handler;
Private $config = Array (
' Host ' = ' localhost ',
' Port ' = 3306,
' User ' = ' root ',
' Password ' = ',
' Database ' = ' test ',
' CharSet ' = ' utf-8 ',
' Target ' = ' sql.sql '
);
Private $tables = Array ();
Private $error;
Private $begin; Start time
/**
* Architecture Method
* @param array $config
*/
Public function __construct ($config = Array ())
{
$this->begin = Microtime (true);
$config = Is_array ($config)? $config: Array ();
$this->config = Array_merge ($this->config, $config);
Start the PDO connection
if (! $this->handler instanceof PDO)
{
Try
{
$this->handler = new PDO ("mysql:host={$this->config[' host ']}:{$this->config[' Port '};d bname={$this config[' database '} ", $this->config[' user '], $this->config[' password ']);
}
catch (Pdoexception $e)
{
$this->error = $e->getmessage ();
return false;
}
catch (Exception $e)
{
$this->error = $e->getmessage ();
return false;
}
}
}

/**
* Backup
* @param array $tables
* @return BOOL
*/
Public Function Backup ($tables = Array ())
{
An array of stored table definition statements
$DDL = Array ();
An array of stored data
$data = Array ();
$this->settables ($tables);
if (!empty ($this->tables))
{
foreach ($this->tables as $table)
{
$DDL [] = $this->getddl ($table);
$data [] = $this->getdata ($table);
}
Start writing
$this->writetofile ($this->tables, $DDL, $data);
}
Else
{
$this->error = ' There are no tables in the database! ';
return false;
}
}

/**
* Set up the table to be backed up
* @param array $tables
*/
Private Function settables ($tables = Array ())
{
if (!empty ($tables) && Is_array ($tables))
{
Back up the specified table
$this->tables = $tables;
}
Else
{
Back up all Tables
$this->tables = $this->gettables ();
}
}

/**
* Enquiry
* @param string $sql
* @return Mixed
*/
Private Function query ($sql = ")
{
$stmt = $this->handler->query ($sql);
$stmt->setfetchmode (Pdo::fetch_num);
$list = $stmt->fetchall ();
return $list;
}

/**
* 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;
}

/**
* Get Table definition statement
* @param string $table
* @return Mixed
*/
Private Function getddl ($table = ")
{
$sql = "SHOW CREATE TABLE ' {$table} '";
$DDL = $this->query ($sql) [0][1]. ';';
return $DDL;
}

/**
* Get Table data
* @param string $table
* @return Mixed
*/
Private Function getData ($table = ")
{
$sql = "SHOW COLUMNS from ' {$table} '";
$list = $this->query ($sql);
Field
$columns = ";
The SQL that needs to be returned
$query = ";
foreach ($list as $value)
{
$columns. = "' {$value [0]} ',";
}
$columns = substr ($columns, 0,-1);
$data = $this->query ("select * from ' {$table} '");
foreach ($data as $value)
{
$DATASQL = ";
foreach ($value as $v)
{
$dataSql. = "' {$v} ',";
}
$DATASQL = substr ($dataSql, 0,-1);
$query. = "INSERT into ' {$table} ' ({$columns}) VALUES ({$dataSql}); \ r \ n";
}
return $query;
}

/**
* Write file
* @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)? ' Backup succeeded! ' time spent '. (Microtime (True)-$this->begin). ' MS ': ' Backup failed! ';
}

/**
* Error message
* @return Mixed
*/
Public Function GetError ()
{
return $this->error;
}

Public Function Restore ($path = ")
{
if (!file_exists ($path))
{
$this->error (' SQL file does not exist! ');
return false;
}
Else
{
$sql = $this->parsesql ($path);
Try
{
$this->handler->exec ($sql);
Echo ' Restore succeeded! Time spent ', (Microtime (True)-$this->begin). ' MS ';
}
catch (Pdoexception $e)
{
$this->error = $e->getmessage ();
return false;
}
}
}

/**
* Parse SQL file as an array of SQL statements
* @param string $path
* @return array|mixed|string
*/
Private Function parsesql ($path = ")
{
$sql = file_get_contents ($path);
$sql = Explode ("\ r \ n", $sql);
First eliminate---comment
$sql = Array_filter ($sql, function ($data)
{
if (Empty ($data) | | preg_match ('/^--. */', $data))
{
return false;
}
Else
{
return true;
}
});
$sql = Implode (' ', $sql);
Delete/**/Comment
$sql = preg_replace ('/\/\*.*\*\//', ' ', $sql);
return $sql;
}
}

http://www.bkjia.com/PHPjc/743927.html www.bkjia.com true http://www.bkjia.com/PHPjc/743927.html techarticle Copy the code as follows:? PHP/** * Database backup Restore class * @author xialeistudioadmin@xialeistudio.net * Class Databasetool */Class Databasetool {private $handler; private $ ...

  • 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.