<?php /*程序功能:mysql數據庫備份功能*/ ini_set('max_execution_time','0'); ini_set('memory_limit','1024M');//加上這兩行,能夠備份大數據,昨晚測了一下公司的一個600M的表,很快就能夠備份成功 $code_type = 'gbk'; header("Content-type:text/html;charset=$code_type"); header("Content-disposition: filename=backup.sql");//所保存的文件名 header("Content-type: application/octetstream"); header("Pragma: no-cache"); header("Expires: 0"); $conn = mysql_connect("localhost","root","root"); $db = mysql_select_db($dbname,$conn); mysql_query("set names $code_type"); $dbname="test";//數據庫名 $flag = '1';//1:所有備份,2:只備份表結構,3:只備份數據 echo back_database($dbname,$conn,$flag);//備份數據庫 //開始備份 function back_database($dbname,$conn,$flag='1'){ $crlf="\r\n"; $str = ''; $now = date('Y年m月d日H點i分s秒',time()); $str .= "$crlf--$crlf-- 數據庫: `$dbname`$crlf--$crlf-- 導出日期: `$now`$crlf--$crlf"; $str .= "$crlf--$crlf-- 做者: ****$crlf--$crlf-- QQ: 1019822077$crlf--$crlf"; $str .= "-- blog: http://hi.baidu.com/woaidelphi/blog$crlf--$crlf"; $str .= "SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\";$crlf"; $tables = mysql_list_tables($dbname,$conn); $num_tables = mysql_numrows($tables);//表的總數 $i = 0; while($i<$num_tables){//循環全部的表 $table = mysql_tablename($tables,$i); //備份表結構 if($flag=='1' or $flag=='2'){ $query = mysql_query("SHOW CREATE TABLE $table"); $row = mysql_fetch_row($query); $str .= "-- --------------------------------------------------------$crlf$crlf"; $str .= "--$crlf-- 表的結構 `$table` $crlf--$crlf"; $str .= $row[1].";$crlf--$crlf"; } //備份表內容 if($flag=='1' or $flag=='3'){ $str .= "--$crlf-- 導出表中的數據 `$table` $crlf--$crlf"; $str .= get_table_content($dbname,$table); $str .= "$crlf$crlf"; } $i++; } return $str; } //獲得表中的記錄sql function get_table_content($dbname,$table){ $crlf = "\r\n"; $schema_create = ""; $temp = ""; $result = mysql_db_query($dbname,"SELECT * FROM $table"); $i = 0; while($row = mysql_fetch_row($result)){ $schema_insert = "INSERT INTO $table VALUES ("; for($j=0; $j<mysql_num_fields($result);$j++){ if(!isset($row[$j])) $schema_insert .= " NULL,"; elseif($row[$j] != "") $schema_insert .= " '".addslashes($row[$j])."',"; else $schema_insert .= " '',"; } $schema_insert = ereg_replace(",$", "", $schema_insert); $schema_insert .= ");$crlf"; $temp = $temp.$schema_insert ; $i++; } return $temp; }