Php backup mysql database program code

Source: Internet
Author: User
Tags mysql backup
In our development, database backup is a very important part. Let's share two php backup mysql database classes. If you have any need, you can modify them.

In our development, database backup is a very important part. Let's share two php backup mysql database classes. If you have any need, you can modify them.

First look at the backup class file

Backdata. class. php:

The Code is as follows:

/*
*
* A simple Mysql backup data class
*
*/
Class backupData {
Private $ mysql_link; // link ID
Private $ dbName; // Database Name
Private $ dataDir; // directory where data is 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 = '') {// The table does not exist
Continue;
}

****** ********
// If a table exists, delete it first.
$ Sqls. = "drop table if exists $ tablename; n ";
// Read the table structure
$ Rs = mysql_query ("show create table $ tablename", $ this-> mysql_link );
$ Row = mysql_fetch_row ($ rs );
// Obtain the table structure as an SQL statement
$ Sqls. = $ row ['1']. "; nn ";
Unset ($ rs );
Unset ($ row );

// ************************ The second half of the SQL statement is formed ******* *******
// Query all the data in the table
$ Rs = mysql_query ("select * from $ tablename", $ this-> mysql_link );
// Number of fields in the table
$ Field = mysql_num_fields ($ rs );
// Form this SQL statement: "INSERT INTO 'groups' VALUES ('1499e0ca25988d', 'directory','', '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 a file
$ Filehandle = fopen ($ backfilepath, "w ");
Fwrite ($ filehandle, $ sqls );
Fclose ($ filehandle );
}
Private function delarray ($ array) {// process the incoming array
Foreach ($ array as $ tables ){
If ($ tables = '*') {// All tables (the table name cannot be an array in the conventional 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

The Code is as follows:
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. You only need a link ID.
// If you want to back up all the tables in a database during data backup, write as follows:
$ Dbbck-> backupTables ("cms", "./", array ('*'));
// When backing up data, if you want to back up only one table in a database, you can write as follows:
$ Dbbck-> backupTables ("cms", "./", array ('user '));
// When backing up data, if you want to back up multiple tables in a database, you can write as follows:
$ Dbbck-> backupTables ("cms", "./", array ('user', 'acl', 'in oin '));
// Annotation: $ dbbck-> backupTables ("parameter 1", "parameter 2", array,
Parameter 1: Database Name,
Parameter 2: Location of the backup data to be stored (that is, the directory address)
Third: the tables you want to save


Let's share a database backup class.

The Code is as follows:

/**
* Description: This type is applicable to database backup for small websites and built-in mysql connections. You only need to configure data connections simply.
* And the storage backup location.
* Perform the following operations after the class is real-listed and connected to the database
* Get_db_table ($ database) obtains all data tables.
* Export_ SQL ($ table, $ subsection = 0) generates an SQL file. Note that the generated SQL file is saved only to the server directory and is not downloaded.
* Import_ SQL ($ dir) only import SQL files in the server directory to restore Data
* This type is easy to create and can be spread at will. If you have any suggestions for this type, please send an email to the shrimps.
* @ Author Zhao Hongjian [youtian shrimp]
* Email: 328742379@qq.com
* Qq chat group: 69574955 juyitang-Online page creation
*/

Class data {
Public $ data_dir = "class/"; // path of the backup file
Public $ transfer = ""; // temporarily store SQL statements. [do not assign values to this attribute. Otherwise, an incorrect SQL statement is generated.]

/**
* Database connection
* @ Param string $ host Name
* @ Param string $ user Username
* @ Param string $ pwd Password
* @ Param string $ db select the Database Name
* @ Param string $ charset encoding method
*/
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 table to be backed up
* @ Return $ tabledump: SQL statement generated
*/
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;
}

/**
* List tables in a database
* @ Param database $ name of the database to be operated on
* @ Return array $ database table in the dbarray list
*/
Public function get_db_table ($ database ){
$ Result = mysql_list_tables ($ database );
While ($ tmparry = mysql_fetch_row ($ result )){
$ Dbarry [] = $ tmparry [0];
}
Return $ dbarry;
}

/**
* Verify whether 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 If ($ filearry [$ I]! = '.' | $ Filearry! = '..'){
@ Unlink ($ dir. $ filearry [$ I]);
}
}
}
}
Return true;
}
/**
* Write data to a file
* @ Param file $ filename file name
* @ Param string $ str information to be written
* @ Return booln return true if the write is successful; otherwise, false
*/
Private function write_ SQL ($ filename, $ str ){
$ Re = true;
If (! @ $ Fp = fopen ($ filename, "w +") {$ re = false; echo "An error occurred while opening the file. Backup failed! ";}
If (! @ Fwrite ($ fp, $ str) {$ re = false; echo "An error occurred while writing information. Backup failed! ";}
If (! @ Fclose ($ fp) {$ re = false; echo "An error occurred while closing the file. Backup failed! ";}
Return $ re;
}

/**
* Generate an SQL File
* @ Param string $ SQL statement
* @ Param number $ subsection volume size, in kb, 0 indicates no volume sharding
*/
Public function export_ SQL ($ table, $ subsection = 0 ){
If (! $ This-> check_write_dir ($ this-> data_dir) {echo 'you do not have permission to operate the directory, backup failed '; return false ;}
If ($ subsection = 0 ){
If (! Is_array ($ table )){
$ This-> set_ SQL ($ table, 0, $ this-> transfer );
} Else {
For ($ I = 0; $ 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 $ Tmparry = $ this-> set_ SQL ($ table [$ I], $ subsection, $ this-> transfer );
$ Sqlarry = array_merge ($ sqlarry, $ tmparry );
}
$ Sqlarry [] = $ this-> transfer;
}
For ($ I = 0; $ I $ Filename = $ this-> data_dir.date ("ymd", time (). '_ part'. $ I.'. SQL ';
If (! $ This-> write_ SQL ($ filename, $ sqlarry [$ I]) {return false ;}
}
}
Return true;
}
/**
* Load an SQL File
* @ Param diretory $ dir
* @ Return booln
* Note: Do not store other files in the directory or directory.
* To save recovery time
*/
Public function import_ SQL ($ dir ){
If ($ link = opendir ($ dir )){
$ Filearry = scandir ($ dir );
$ Pattern = "_ part [0-9] +. SQL $ | _ all. SQL $ ";
For ($ I = 0; $ 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

The Code is as follows:

// $ D = new data ();

// Connect to the database
// If (! $ D-> connect_db ('localhost', 'root', '', 'guestbook', 'gbk ')){
// Echo 'database connection failed ';
/

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.