|
一、備份數(shù)據(jù)庫(kù)并下載到本地【db_backup.php】
復(fù)制代碼 代碼如下:
<?php
// 設(shè)置SQL文件保存文件名
$filename=date("Y-m-d_H-i-s")."-".$cfg_dbname.".sql";
// 所保存的文件名
header("Content-disposition:filename=".$filename);
header("Content-type:application/octetstream");
header("Pragma:no-cache");
header("Expires:0");
// 獲取當(dāng)前頁(yè)面文件路徑,SQL文件就導(dǎo)出到此文件夾內(nèi)
$tmpFile = (dirname(__FILE__))."http://".$filename;
// 用MySQLDump命令導(dǎo)出數(shù)據(jù)庫(kù)
exec("mysqldump -u$cfg_dbuser -p$cfg_dbpwd --default-character-set=utf8 $cfg_dbname > ".$tmpFile);
$file = fopen($tmpFile, "r"); // 打開(kāi)文件
echo fread($file,filesize($tmpFile));
fclose($file);
exit;
?>
二、還原數(shù)據(jù)庫(kù)【db_restore.php】
復(fù)制代碼 代碼如下:
<form id="form1" name="form1" method="post" action="">
【數(shù)據(jù)庫(kù)SQL文件】:<input id="sqlFile" name="sqlFile" type="file" />
<input id="submit" name="submit" type="submit" value="還原" />
</form>
<?php
// 我的數(shù)據(jù)庫(kù)信息都存放到config.php文件中,所以加載此文件,如果你的不是存放到該文件中,注釋此行即可;
require_once((dirname(__FILE__).'/../../include/config.php'));
if ( isset ( $_POST['sqlFile'] ) )
{
$file_name = $_POST['sqlFile']; //要導(dǎo)入的SQL文件名
$dbhost = $cfg_dbhost; //數(shù)據(jù)庫(kù)主機(jī)名
$dbuser = $cfg_dbuser; //數(shù)據(jù)庫(kù)用戶(hù)名
$dbpass = $cfg_dbpwd; //數(shù)據(jù)庫(kù)密碼
$dbname = $cfg_dbname; //數(shù)據(jù)庫(kù)名
set_time_limit(0); //設(shè)置超時(shí)時(shí)間為0,表示一直執(zhí)行。當(dāng)php在safe mode模式下無(wú)效,此時(shí)可能會(huì)導(dǎo)致導(dǎo)入超時(shí),此時(shí)需要分段導(dǎo)入
$fp = @fopen($file_name, "r") or die("不能打開(kāi)SQL文件 $file_name");//打開(kāi)文件
mysql_connect($dbhost, $dbuser, $dbpass) or die("不能連接數(shù)據(jù)庫(kù) $dbhost");//連接數(shù)據(jù)庫(kù)
mysql_select_db($dbname) or die ("不能打開(kāi)數(shù)據(jù)庫(kù) $dbname");//打開(kāi)數(shù)據(jù)庫(kù)
echo "<p>正在清空數(shù)據(jù)庫(kù),請(qǐng)稍等....<br>";
$result = mysql_query("SHOW tables");
while ($currow=mysql_fetch_array($result))
{
mysql_query("drop TABLE IF EXISTS $currow[0]");
echo "清空數(shù)據(jù)表【".$currow[0]."】成功!<br>";
}
echo "<br>恭喜你清理MYSQL成功<br>";
echo "正在執(zhí)行導(dǎo)入數(shù)據(jù)庫(kù)操作<br>";
// 導(dǎo)入數(shù)據(jù)庫(kù)的MySQL命令
exec("mysql -u$cfg_dbuser -p$cfg_dbpwd $cfg_dbname < ".$file_name);
echo "<br>導(dǎo)入完成!";
mysql_close();
}
?>
php技術(shù):PHP備份/還原MySQL數(shù)據(jù)庫(kù)的代碼,轉(zhuǎn)載需保留來(lái)源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。