MySQL backup using PHP)

Source: Internet
Author: User
Tags mysql backup
I have read phpMyAdmin and discuz! So I copied discuz! The following method is used to back up the database. (Thanks to discuz! Developers)

There are two ways to back up the database: one is to back up the structure of the database, the other is to back up the structure and all the data, of course, the second method is good, however, I have done everything to consider possible needs.

/****** Back up the database structure ******/

/*
Function Name: table2sql ()
Function: converts the table structure to SQL
Function parameter: $ table: name of the table to be extracted
Return Value: return the extracted results, SQL set
Function Author: heiyeluren
*/

Function table2sql ($ table)
{
Global $ dB;
$ Tabledump = "Drop table if exists $ table;/N ";
$ Createtable = $ db-> query ("show create table $ table ");
$ Create = $ db-> fetch_row ($ createtable );
$ Tabledump. = $ create [1]. ";/n ";
Return $ tabledump;
}

/****** Back up the database structure and all data ******/
/*
Function Name: data2sql ()
Function: converts the table structure and data into SQL statements.
Function parameter: $ table: name of the table to be extracted
Return Value: return the extracted results, SQL set
Function Author: heiyeluren
*/
Function data2sql ($ table)
{
Global $ dB;
$ Tabledump = "Drop table if exists $ table;/N ";
$ Createtable = $ db-> query ("show create table $ table ");
$ Create = $ db-> fetch_row ($ createtable );
$ Tabledump. = $ create [1]. ";/n ";

$ Rows = $ db-> query ("select * from $ table ");
$ Numfields = $ db-> num_fields ($ rows );
$ Numrows = $ db-> num_rows ($ rows );
While ($ ROW = $ db-> fetch_row ($ rows ))
{
$ Comma = "";
$ Tabledump. = "insert into $ table values (";
For ($ I = 0; $ I <$ numfields; $ I ++)
{
$ Tabledump. = $ Comma. "'". mysql_escape_string ($ row [$ I]). "'";
$ Comma = ",";
}
$ Tabledump. = ");/N ";
}
$ Tabledump. = "/N ";

Return $ tabledump;
}

/****** Specific implementation operations ******/
Well, since we have written all the code, how can we implement backup in a specific program? Let's look at the following code.

/* Back up the database */
// Note: The following database operations use the phplib dB class.

// Define the data table to be saved, the prefix, and where to save the data table
$ Tables = array ('us _ sort ', 'us _ download', 'us _ article', 'us _ guestbook'); // defines the data table to be saved, an array
$ Prefix = 'us _ '; // prefix of the. SQL file to be saved
$ Saveto = 'server'; // Where to save it, whether it is local or on the server. The default value is server.
$ Back_mode = 'all'; // you can specify whether to back up all the data or only store the database structure.
$ Admin = 'heiyeluren'; // Administrator name
$ Admin_email = 'heiyeluren @ 163.com '; // administrator email

// Define the data storage file name
$ Local_filename = $ prefix. Date ('ymd _ his ').'. SQL "';
If (! $ Filename) {$ filename = $ db_backup_path. $ prefix. Date ('ymd _ His _ '). create_check_code (4). ". SQL ";}
$ Filename = $ prefix. Date (ymd_his). create_check _ code (6). ". SQL"; // file name saved on the server
// Pay attention to the create_check_code () function next to it. This is a function that generates random codes. For details, refer:
// Http://blog.csdn.net/heiyeshuwu/archive/2005/01/26/268446.aspx

// Obtain the database structure and data content
Foreach ($ tables as $ table)
{
If ($ back_mode = 'all') {$ sqldump. = data2sql ($ table );}
If ($ back_mode = 'table') {$ sqldump. = table2sql ($ table );}
}

// Save the data if it is not empty
If (TRIM ($ sqldump ))
{
// Write the start information
$ Sqldump =
"# --------------------------------------------------------/N ".
"# Data table backup/N ".
"#/N ".
"# Server: $ db-> host/N ".
"# Database: $ db-> database/N ".
"# Backup number:". create_sess_id (). "/N". // here is a function for generating session IDs.
"# Backup time:". time_to_date ('', 6)."/N ". // This is the function for obtaining the current time.
"#/N ".
"# Administrator: $ admin ($ admin_email)/n". // administrator username and email address
"# $ Copyright/N ".
"# --------------------------------------------------------/N ".
$ Sqldump;

// Save to local
If ($ saveto = "local ")
{
Ob_end_clean ();
Header ('content-encoding: none ');
Header ('content-type: '. (strpos ($ http_server_vars ['HTTP _ user_agent'], 'msi ')? 'Application/etetstream': 'application/octet-stream '));
Header ('content-Disposition: '. (strpos ($ http_server_vars ['HTTP _ user_agent'], 'msi ')? 'Inline; ': 'attachment;'). 'filename = "'. $ local_filename );
Header ('content-length: '. strlen ($ sqldump ));
Header ('pragma: No-cache ');
Header ('expires: 0 ');
Echo $ sqldump;
}
// Save to local end

// Save it to the server
If ($ saveto = "server ")
{
If ($ filename! = "")
{
@ $ Fp = fopen ($ filename, "W + ");
If ($ FP)
{
@ Flock ($ FP, 3 );
If (@! Fwrite ($ FP, $ sqldump ))
{
@ Fclose ($ FP );
Exit_msg ("the data file cannot be saved to the server. Check whether you have the write permission on the directory attribute. ");
}
Else
{
Exit_msg ("data is successfully backed up to the server $ filename. ");
}
}
Else
{
Exit_msg ("unable to open the directory you specified". $ filename. ", check whether the directory exists or has the corresponding permission ");
}
}
Else
{
Exit_msg ("You have not entered the backup file name. Please return and modify it. ");
}
}
// Save to the end of the server
}
Else
{
Exit_msg ("the data table has no content ");
}

/* End the backup database */

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.