PHP MySQL database backup and data restore class

Source: Internet
Author: User
Tags php mysql mysql database

/**
* Description, this class is suitable for small web site database backup, built-in MySQL connection, simply configure the data connection
* and the location of the storage backup can be.
* Class is materialized and you can connect to the database to perform the following actions
* Get_db_table ($database) access to all data sheets
* Export_sql ($table, $subsection =0)) generates SQL files, noting that generating SQL files is only saved to the server directory and does not provide downloads
* IMPORT_SQL ($DIR) Recover data import only SQL files in the server directory
* This kind of production is simple, can spread arbitrarily, how do you have any proposal to this class, please send mail to shrimp
* @author Zhaohongjian [tian Xiao Shrimp]
* email:328742379@qq.com
* QQ Exchange Group: 69574955 Juyi Hall-Web page making hand
*/

The code is as follows Copy Code

Class Data {
Public $data _dir = "class/"; The path where the backup files are stored
Public $transfer = ""; Temporarily store sql[do not assign a value to this property, or you will generate an incorrect SQL statement.

/**
 * database connection
 * @param string $host database host name
 * @param string $user user name
 * @param string $pwd   Password
 * @param string $db    Select database name
 * @param string $charset encoding
 */
&NB Sp;function connect_db ($host, $user, $pwd, $db, $charset = ' GBK ') {
  if (! $conn = mysql_connect ($host, $user , $pwd)) {
   return false;
  }
  mysql_select_db ($db);
   mysql_query ("Set names $charset");
  return true;
 }

/**
* Generate SQL statements
* @param $table The tables to be backed up
* @return $tabledump generated SQL statements
*/
Public Function Set_sql ($table, $subsection =0,& $tabledom = ') {
$tabledom. = "DROP table if exists $table";
$createtable = mysql_query ("Show create Table $table");
$create = Mysql_fetch_row ($createtable);
$create [1] = Str_replace ("", "", $create [1]);
$create [1] = Str_replace ("", "", $create [1]);

$tabledom. = $create [1]. ";";

$rows = mysql_query ("SELECT * from $table");
$numfields = Mysql_num_fields ($rows);
$numrows = mysql_num_rows ($rows);
$n = 1;
$sqlarry = Array ();
while ($row = Mysql_fetch_row ($rows)) {
$comma = "";
$tabledom. = "INSERT into $table values (";
for ($i = 0; $i < $numfields; $i + +)
{
$tabledom. = $comma. "'". Mysql_escape_string ($row [$i]). "'";
$comma = ",";
}
$tabledom. = ")";
if ($subsection!= 0 && strlen ($this->transfer) >= $subsection *1000) {
$sqlarry [$n]= $tabledom;
$tabledom = '; $n + +;
}
}
return $sqlarry;
}

/**
* Tables in the list database
* @param database $database The names of the databases to be manipulated
* @return Array $dbarray list of database tables
*/
Public Function get_db_table ($database) {
$result = Mysql_list_tables ($database);
while ($tmparry = Mysql_fetch_row ($result)) {
$dbarry [] = $tmparry [0];
}
return $dbarry;
}

/**
* Verify that the directory is valid
* @param diretory $dir
* @return Booln
*/
function Check_write_dir ($dir) {
if (!is_dir ($dir)) {@mkdir ($dir, 0777);}
if (Is_dir ($dir)) {
if ($link = Opendir ($dir)) {
$filearry = Scandir ($dir);
for ($i =0; $i <count ($filearry); $i + +) {
if ($filearry [$i]!= '. ' | | $filearry!= '. ') {
@unlink ($dir. $filearry [$i]);
}
}
}
}
return true;
}
/**
* Write data to a file
* @param file $filename filename
* @param string $str the information to write
* Returns True @return Booln write success, or false
*/
Private Function Write_sql ($filename, $str) {
$re = true;
if (!@ $fp =fopen ($filename, "w+")) {$re =false echo "encountered an error opening the file, Backup failed!";}
if (! @fwrite ($FP, $str)) {$re =false echo encountered an error while writing the message, the backup failed! ";}
if (! @fclose ($fp)) {$re =false echo has encountered an error closing the file, backup failed! ";}
return $re;
}

/**
* Generate SQL file
* @param string $sql SQL statement
* @param number $subsection the size of the volume, in kilobytes, 0 for non-volume
*/
Public Function Export_sql ($table, $subsection =0) {
if (! $this->check_write_dir ($this->data_dir)) {echo ' You do not have permission to manipulate directories, backup failed '; return false;}
if ($subsection = = 0) {
if (!is_array ($table)) {
$this->set_sql ($table, 0, $this->transfer);
}else{
for ($i =0; $i <count ($table); $i + +) {
$this->set_sql ($table [$i],0, $this->transfer);
}
}
$filename = $this->data_dir.date ("Ymd", Time ()). ' _all.sql ';
if (! $this->write_sql ($filename, $this->transfer)) {return false;}
}else{
if (!is_array ($table)) {
$sqlarry = $this->set_sql ($table, $subsection, $this->transfer);
$sqlarry [] = $this->transfer;
}else{
$sqlarry = Array ();
for ($i =0; $i <count ($table); $i + +) {
$tmparry = $this->set_sql ($table [$i], $subsection, $this->transfer);
$sqlarry = Array_merge ($sqlarry, $tmparry);
}
$sqlarry [] = $this->transfer;
}
for ($i =0; $i <count ($sqlarry); $i + +) {
$filename = $this->data_dir.date ("Ymd", Time ()). ' _part '. $i. '. sql ';
if (! $this->write_sql ($filename, $sqlarry [$i])) {return false;}
}
}
return true;
}
/**
* Load SQL file
* @param diretory $dir
* @return Booln
* Note: Please do not store other files or directories below the directory
* To save time for recovery
*/
Public Function Import_sql ($dir) {
if ($link = Opendir ($dir)) {
$filearry = Scandir ($dir);
$pattern = "_part[0-9]+.sql$|_all.sql$";
for ($i =0; $i <count ($filearry); $i + +) {
if (eregi ($pattern, $filearry [$i])) {
$sqls =file ($dir. $filearry [$i]);
foreach ($sqls as $sql) {
Str_replace ("", "", $sql);
Str_replace ("", "", $sql);
if (!mysql_query trim ($sql)) return false;
}
}
}
return true;
}
}

}

Application method

  code is as follows copy code

//$d = new Data ();

//Connection Database
//if (! $d->connect_db (' localhost ', ' root ', ', ', ' Guestbook ', ' GBK ')) {
// echo ' database connection failed ';

//Find all data tables in the database
//$tablearry = $d->get_db_table (' guestbook ');

//backup and generate SQL file
//if (! $d->export_sql ($tablearry)) {
// echo ' backup failed ';
//}else{
// echo ' Backup successful ';
//}

//Restore Import SQL Folder
//if ($d->import_sql ($d->data_dir)) {
// echo ' restore success ';
//}else{
//  Echo ' recovery failed ';
//}

Related Article

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.