仿照phpMyAdmin写的一个简单MYSQL备份、还原程序,已测试通过(不适合复杂结构),仅供参考!
config.php文件:
$dbhost="localhost";
$dbuser="root";
$dbpass="";
$dbname="test";
$filename="backup_".$dbname."_2002_10_16.sql";
$conn = mysql_pconnect($dbhost,$dbuser,$dbpass);
@mysql_select_db($dbname,$conn) or die(mysql_error());
set_time_limit(0);
?>
backup.php文件:
include("config.php");
$tables = mysql_list_tables($dbname);
$num_tables = @mysql_numrows($tables);
//header("Content-type: text/plain");
header("Content-Type: application/octetstream");
if(preg_match("/MSIE 5.5/", $HTTP_USER_AGENT))
{
header("Content-Disposition: filename=$filename");
}
else
{
header("Content-Disposition: attachment;filename=$filename");
}
echo "# \n";
echo "# Database backup file \n";
echo "# copyright @ phpteam 20002-2003 \n";
echo "# \n";
echo "# Host : " . $dbhost ."\n";
echo "# Database: " . $dbname ."\n";
echo "# Date : " . date("d-M-Y",time()) . "\n";
echo "# \n\n\n";
$i=0;
while ($i<$num_tables)
{
$table = mysql_tablename($tables,$i);
echo "# \n";
echo "# Table structure for table '$table' \n";
echo "# \n\n";
// table structure
$struc = "DROP TABLE IF EXISTS ".$table.";\n";
$struc .= "CREATE TABLE $table (\n";
$query = "SHOW FIELDS FROM $table";
$result = mysql_query($query);
while ($row=mysql_fetch_array($result))
{
$struc .= " $row[Field] $row[Type]";
if(!empty($row["Default"]))
{
$struc .= " DEFAULT '$row[Default]'";
}
if($row["Null"] != "YES")
{
$struc .= " NOT NULL";
}
if($row["Extra"] != "")
{
$struc .= " $row[Extra]";
}
$struc .= ",\n";
}
$query = "SHOW KEYS FROM $table";
$result = mysql_query($query);
$pkey_exist = mysql_num_rows($result);
if($pkey_exist!=0)
{
$pkey = mysql_result($result,0,'column_name');
$struc .= " PRIMARY KEY ($pkey)\n";
}
else
{
// replace ,\n
$struc = substr($struc,0, strlen($struc)-2);
$struc .= "\n";
}
echo $struc;
echo ");\n\n";
// data
echo "# \n";
echo "# Dumping data for table '$table' \n";
echo "# \n\n";
$query = "select * from $table";
$result = mysql_query($query);
$j = 0;
while($row=mysql_fetch_row($result))
{
$data .= "INSERT INTO $table VALUES(";
for($k=0; $k {
if (!isset($row[$k]))
{
$data .= " NULL,";
}
elseif($row[$k]!="")
{
$data .= " '".addslashes($row[$k])."',";
}
else
{
$data .= " '',";
}
}
// replace ,\n
$data = substr($data,0, strlen($data)-1);
$data .= ");\n";
$j++;
}
echo $data."\n";
$data = "";
$i++;
}
?>
import.php文件:
include("config.php");
$fp = fopen($filename, "r");
while($buffer = fgets($fp, 10000))
{
$buffer = trim($buffer);
if(!empty($buffer) && substr($buffer,0,1) != "#")
{
if(substr($buffer,-2,2)==");")
{
$query .= $buffer;
$result = mysql_query($query);
$query = "";
}
else
{
$query .= $buffer;
}
}
}
fclose($fp);
echo $dbname." has restored!";
?>
阅读(2221) | 评论(0) | 转发(0) |