如何在php中备份数据库? [英] How to take backup of database in php?
本文介绍了如何在php中备份数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在做一些与金融相关的项目,为此我正在使用 mysql 数据库.有人可以建议我如何在每次操作后备份数据库吗?
I am doing some projects related to finance and for that i am using mysql database.Can any one suggest me how to take backup of database after each operation?
推荐答案
在这段代码中,在第一行输入主机、用户名、密码、数据库或表名: backup_tables('localhost','useranme','密码','database_or_table_name');
In this code, enter host, username, password, database or table name in first line : backup_tables('localhost','useranme','password','database_or_table_name');
您将在 htdocs 中得到一个名为 db-backup.......
的文件.这对我有用.试试这个代码:
You will get a file named db-backup.......
in htdocs.
This works for me. Try This code:
<?php
// Enter database name here
backup_tables('localhost','useranme','password','database_or_table_name');
/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '*')
{
$link = mysql_connect($host,$user,$pass);
mysql_select_db($name,$link);
//get all of the tables
if($tables == '*')
{
$tables = array();
$result = mysql_query('SHOW TABLES');
while($row = mysql_fetch_row($result))
{
$tables[] = $row[0];
}
}
else
{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
//cycle through
$return = "";
foreach($tables as $table)
{
$result = mysql_query('SELECT * FROM '.$table);
$num_fields = mysql_num_fields($result);
$return.= 'DROP TABLE IF EXISTS '.$table.';';
$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
$return.= "\n\n".$row2[1].";\n\n";
for ($i = 0; $i < $num_fields; $i++)
{
while($row = mysql_fetch_row($result))
{
$return.= 'INSERT INTO '.$table.' VALUES(';
for($j=0; $j < $num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = ereg_replace("\n","\\n",$row[$j]);
if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
if ($j < ($num_fields-1)) { $return.= ','; }
}
$return.= ");\n";
}
}
$return.="\n\n\n";
}
//save file
$handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');
fwrite($handle,$return);
fclose($handle);
}
?>
这篇关于如何在php中备份数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文