Copy codeThe Code is as follows:
<? Php
/**
* Database backup and Restoration
* @ Author xialeistudio <admin@xialeistudio.net>
* 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']}; dbname = {$ 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 ())
{
// Store the array of table definition statements
$ Ddl = array ();
// 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 = 'no table exists in the Database! ';
Return false;
}
}
/**
* Set the table to be backed up
* @ Param array $ tables
*/
Private function setTables ($ tables = array ())
{
If (! Empty ($ tables) & is_array ($ tables ))
{
// Backup the specified table
$ This-> tables = $ tables;
}
Else
{
// Back up all tables
$ This-> tables = $ this-> getTables ();
}
}
/**
* Query
* @ Param string $ SQL
* @ Return mixed
*/
Private function query ($ SQL = '')
{
$ Stmt = $ this-> handler-> query ($ SQL );
$ Stmt-> setFetchMode (PDO: FETCH_NUM );
$ List = $ stmt-> fetchAll ();
Return $ list;
}
/**
* Getting 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 statements
* @ Param string $ table
* @ Return mixed
*/
Private function getDDL ($ table = '')
{
$ SQL = "SHOW CREATE TABLE '{$ table }'";
$ Ddl = $ this-> query ($ SQL) [0] [1]. ';
Return $ ddl;
}
/**
* Getting table data
* @ Param string $ table
* @ Return mixed
*/
Private function getData ($ table = '')
{
$ SQL = "SHOW COLUMNS FROM '{$ table }'";
$ List = $ this-> query ($ SQL );
// Field
$ Columns = '';
// The SQL statement 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;
}
/**
* Writing files
* @ 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 successful! 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 'restored successfully! Time spent ', (microtime (true)-$ this-> begin). 'ms ';
}
Catch (PDOException $ e)
{
$ This-> error = $ e-> getMessage ();
Return false;
}
}
}
/**
* Parse the 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 );
// Remove first -- 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;
}
}