This example describes how to implement MySQL database backup in php. Share it with you for your reference. The specific analysis is as follows: this is a very simple class file that uses php to back up the mysql database. we only need to simply configure the connection address username and database to share the php backup database class.
<? Php/***** @ name php backup database * @ param string $ DbHost connection host * @ param string $ DbUser username * @ param string $ DbPwd connection password * @ param string $ DbName the name of the database * @ param string $ saveFileName to be backed up, the default file is saved in the current folder, which is differentiated by date * @ return Null * @ example backupMySqlData ('localhost', 'root', '123', 'yourdbname '); **/function backupMySqlData ($ DbHost, $ DbUser, $ DbPwd, $ DbName, $ saveFileName = '') {header (" Content-type: text/html; charset = utf-8 "); error_reporting (0); set_time_limit (0); echo 'data backup, please wait ......
'; $ Link = mysql_connect ($ DbHost, $ DbUser, $ DbPwd) or die ('database connection failed :'. mysql_error (); mysql_select_db ($ DbName) or die ('database connection failed :'. mysql_error (); mysql_query ('set names utf8'); // declare the variable $ isDropInfo = ''; $ insertSQL =''; $ row = array (); $ tables = array (); $ tableStructure = array (); $ fileName = ($ saveFileName? $ SaveFileName: 'MySQL _ data_bakeup _'). date ('ymdhis '). '. SQL '; // enumerate all TABLES in the database $ res = mysql_query ("SHOW TABLES FROM $ DbName"); while ($ row = mysql_fetch_row ($ res )) {$ tables [] = $ row [0];} mysql_free_result ($ res); // enumerate the statement foreach ($ tables as $ val) for creating all tables) {$ res = mysql_query ("show create table $ val", $ link); $ row = mysql_fetch_row ($ res); $ isDropInfo = "drop table if exists '". $ val. "'; \ r \ n"; $ ta BleStructure = $ isDropInfo. $ row [1]. "; \ r \ n"; file_put_contents ($ fileName, $ tableStructure, FILE_APPEND); mysql_free_result ($ res );} // enumerate the INSERT statements of all tables foreach ($ tables as $ val) {$ res = mysql_query ("select * from $ val "); // insert while ($ row = mysql_fetch_row ($ res) {$ sqlStr = "insert '". $ val. "'values ("; foreach ($ row as $ v) {$ sqlStr. = "'$ V'," ;}// remove the last comma $ sqlStr = substr ($ sq LStr, 0, strlen ($ sqlStr)-1); $ sqlStr. = "); \ r \ n"; file_put_contents ($ fileName, $ sqlStr, FILE_APPEND);} mysql_free_result ($ res);} echo 'data backup successful! ';} // Call this method backupMySqlData ('localhost', 'root', '123', 'youdbname');?>
The above is all the content of this article. I hope you will like it.