How to Use PHP to implement MySQL backup?

Source: Internet
Author: User
Tags mysql backup

The following article describes how to use PHP to implement MySQL backup. We all know that using PHP to implement MySQL backup is quite frequent, the following article describes how to use PHP to implement 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.

Backup 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

  1. function table2sql($table)   
  2. {  
  3. global $db;  
  4. $tabledump = "DROP TABLE IF EXISTS $table;\n";  
  5. $createtable = $db->query("SHOW CREATE TABLE $table");  
  6. $create = $db->fetch_row($createtable);  
  7. $tabledump .= $create[1].";\n\n";   
  8. return $tabledump;  
  9. }  

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

 
 
  1. function data2sql($table)   
  2. {  
  3. global $db;  
  4. $tabledump = "DROP TABLE IF EXISTS $table;\n";  
  5. $createtable = $db->query("SHOW CREATE TABLE $table");  
  6. $create = $db->fetch_row($createtable);  
  7. $tabledump .= $create[1].";\n\n";  
  8. $rows = $db->query("SELECT * FROM $table");  
  9. $numfields = $db->num_fields($rows);  
  10. $numrows = $db->num_rows($rows);  
  11. while ($row = $db->fetch_row($rows))  
  12. {  
  13. $comma = "";  
  14. $tabledump .= "INSERT INTO $table VALUES(";  
  15. for($i = 0; $i < $numfields; $i++)   
  16. {  
  17. $tabledump .= $comma."'".MySQL_escape_string($row[$i])."'";  
  18. $comma = ",";  
  19. }  
  20. $tabledump .= ");\n";  
  21. }  
  22. $tabledump .= "\n";  
  23. return $tabledump;  
  24. }  

Specific MySQL operations

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

Back up database

Note: The following database operations use the phplib DB class.

Define the data table to be saved, the prefix, and where to save

$ 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

 
 
  1. foreach($tables as $table)   
  2. {  
  3. if ($back_mode == 'all') { $sqldump .= data2sql($table); }  
  4. 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

 
 
  1. if($saveto == "local")   
  2. {  
  3. ob_end_clean();  
  4. header('Content-Encoding: none');  
  5. header('Content-Type: '.(strpos($HTTP_SERVER_VARS['HTTP_USER_AGENT'], 'MSIE') ? 

    'application/octetstream' : 'application/octet-stream'));  
  6. header('Content-Disposition: '.(strpos($HTTP_SERVER_VARS['HTTP_USER_AGENT'], 'MSIE') ? 

    'inline; ' : 'attachment; ').'filename="'.$local_filename);  
  7. header('Content-Length: '.strlen($sqldump));  
  8. header('Pragma: no-cache');  
  9. header('Expires: 0');  
  10. echo $sqldump;  
  11. }  

Save to local end

Save on server

 
 
  1. if($saveto == "server")   
  2. {  
  3. if($filename != "")   
  4. {  
  5. @$fp = fopen($filename, "w+");  
  6. if ($fp)  
  7. {  
  8. @flock($fp, 3);  
  9. if(@!fwrite($fp, $sqldump))   
  10. {  
  11. @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 <a href = \" $ filename \ "> $ filename </a>. ");

}

}

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 of Database Backup

The above content is an introduction to implementing MySQL backup in PHP. I hope you will get some benefits.

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.