PHP backup MySQL Database program code

Source: Internet
Author: User
Tags one table mysql backup

Look at the Backup class file first

backdata.class.php:

The code is as follows Copy Code

<?php
/*
*
* Simple one MySQL backup data class
*
*/
Class backupdata{
Private $mysql _link;//Link identification
Private $dbName; Database name
Private $dataDir; The directory where the data is to be stored
private $tableNames;//Table name

Public function __construct ($mysql _link) {
$this->mysql_link = $mysql _link;
}
Public Function Backuptables ($dbName, $dataDir, $tableNames) {//Start Backup
$this->dbname = $dbName;
$this->datadir = $dataDir;
$this->tablenames = $tableNames;
$tables = $this->delarray ($this->tablenames);
$sqls = ';
foreach ($tables as $tablename) {
if ($tablename = =) {//table does not exist
Continue
}

Here is the first half of the form SQL **************
If there is a table, delete it first
$sqls. = "DROP TABLE IF EXISTS $tablename; n";
Reading table structure
$rs = mysql_query ("Show CREATE TABLE $tablename", $this->mysql_link);
$row =mysql_fetch_row ($RS);
Get table structure to compose SQL
$sqls. = $row [' 1 ']. "; nn ";
Unset ($RS);
Unset ($row);

The following is the second half of the form SQL **************
Search out all the data in the table
$rs =mysql_query ("SELECT * from $tablename", $this->mysql_link);
Number of fields in a table
$field =mysql_num_fields ($RS);
form This SQL statement: INSERT into ' groups ' VALUES (' 1499e0ca25988d ', ' director ', ', ', ' 0 '); "
while ($rows =mysql_fetch_row ($rs)) {
$comma = ';/comma
$sqls. = "INSERT into ' $tablename ' VALUES (";
for ($i =0; $i < $field; $i + +) {
$sqls. = $comma. "'". $rows [$i]. "'";
$comma = ', ';
}
$sqls. = "); nnn";
}
}
$backfilepath = $this->datadir.date ("Ymdhis", Time ()). SQL ';

Write to File
$filehandle = fopen ($backfilepath, "w");
Fwrite ($filehandle, $SQLS);
Fclose ($filehandle);
}
Private Function Delarray ($array) {//Processing incoming array
foreach ($array as $tables) {
if ($tables = = ' * ') {//All tables (the table name cannot be grouped into an array in the usual way)
$newtables =mysql_list_tables ($this->dbname, $this->mysql_link);
$tableList = Array ();
for ($i = 0; $i < mysql_numrows ($newtables); $i + +) {
Array_push ($tableList, Mysql_tablename ($newtables, $i));
}
$tableList = $tableList;
}else{
$tableList = $array;
Break
}
}
return $tableList;
}
}

?>

Database backup Usage

  code is as follows copy code
require_once" ("backdata.class.php");
$link = @mysql_connect ("localhost", "Database name", "password") or Die (' could not connect to server. ');
mysql_query ("Use CMS", $link);
mysql_query ("Set names UTF8", $link);
$dbbck =new backupdata ($link);//Instantiate it, as long as a link identification on the line
////Back up the data, if you want to back up all the tables in a database, you can write:
$dbbck->backuptables ("CMS", "./", Array (' * '));
//When backing up data, if you want to back up only one table in a database, you can write:
$dbbck->backuptables ("CMS", "./", Array (' user '));
//Backup data, If you want to back up multiple tables in a database, you can write:
$dbbck->backuptables ("CMS", "./", Array (' user ', ' ACL ', ' informatoin '));
//Note: $ Dbbck->backuptables ("Parameter 1", "Parameter 2", Array ()); in,
parameter 1 is: database name,
Parameter 2 is: the location where the backup data is to be stored (that is, the directory address)
The third is: you want to save those tables


To share a database backup class

The code is as follows Copy Code

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

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 $tablen";
$createtable = mysql_query ("Show create Table $table");
$create = Mysql_fetch_row ($createtable);
$create [1] = Str_replace ("n", "", $create [1]);
$create [1] = Str_replace ("T", "", $create [1]);

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

$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. = ") n";
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 ("R", "", $sql);
Str_replace ("n", "", $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 succeeded ';
//}< /p>

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

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.