PHP backup database class sharing
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
/** * * @name php backup database * @param string $DbHost connection host * @param string $DbUser username * @param string $DbPwd connection password * @param string $DbName The database to be backed up * @param string $saveFileName The name of the file to be saved. The default file is saved in the current folder, distinguished by date * @return Null * @example backupMySqlData('localhost', 'root', '123456', '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 is being backed up, 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 variables $isDropInfo = ''; $insertSQL = ''; $row = array(); $tables = array(); $tableStructure = array(); $fileName = ($saveFileName ? $saveFileName : 'MySQL_data_bakeup_') . date('YmdHis') . '.sql';
// Enumerate all tables in this database $res = mysql_query("SHOW TABLES FROM $DbName"); while ($row = mysql_fetch_row($res)) {
$tables[] = $row[0];
} mysql_free_result($res);
// Enumerate the creation statements of all tables foreach ($tables as $val) {
$res = mysql_query("show create table $val", $link); $row = mysql_fetch_row($res);
$isDropInfo = "DROP TABLE IF EXISTS `" . $val . "`;rn"; $tableStructure = $isDropInfo . $row[1] . ";rn";
file_put_contents($fileName, $tableStructure, FILE_APPEND); mysql_free_result($res); }
// Enumerate INSERT statements of all tables foreach ($tables as $val) {
$res = mysql_query("select * from $val");
//Tables with no data will not perform insert while ($row = mysql_fetch_row($res)) {
$sqlStr = "INSERT INTO `".$val."` VALUES (";
foreach($row as $v){
$sqlStr .= "'$v',";
} //Remove the last comma $sqlStr = substr($sqlStr, 0, strlen($sqlStr) - 1); $sqlStr .= ");rn";
file_put_contents($fileName, $sqlStr, FILE_APPEND); } mysql_free_result($res); }
echo 'Data backup successful! '; } // Call this method backupMySqlData('localhost', 'root', '123456', 'YouDbName'); ?> |