有時(shí)候,你的用戶要求添加一個(gè)選項(xiàng),導(dǎo)出整個(gè)數(shù)據(jù)庫到一個(gè)SQL文件。雖然phpMyAdmin,以及Navicat有這個(gè)功能,但你的用戶想要更簡單點(diǎn)怎么辦?
以下是如何一鍵導(dǎo)出MySQL數(shù)據(jù)庫的php代碼。
新建一個(gè)名為backup.php的文件,復(fù)制粘貼以下代碼,然后編輯數(shù)據(jù)庫連接設(shè)置和mysqldump的路徑。有必要的話,你還可以添加一個(gè)backup.php超鏈接到你的程序里:
<A href="backup.php">導(dǎo)出整個(gè)數(shù)據(jù)庫</A>
請(qǐng)注意,第一個(gè)php代碼執(zhí)行的時(shí)候,會(huì)導(dǎo)出zip壓縮后的sql文件,所以此代碼所在文件夾需要可寫的權(quán)限。
如果你沒有寫的權(quán)限,請(qǐng)使用第二個(gè)php代碼,缺點(diǎn)是導(dǎo)出的sql文件不會(huì)被zip壓縮。
此代碼需要可寫權(quán)限:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbname = "cars";
// if mysqldump is on the system path you do not need to specify the full path
// simply use "mysqldump --add-drop-table ..." in this case
$dumpfname = $dbname . "_" . date("Y-m-d_H-i-s").".sql";
$command = "C:\\xampp\\mysql\\bin\\mysqldump --add-drop-table --host=$hostname
--user=$username ";
if ($password)
$command.= "--password=". $password ." ";
$command.= $dbname;
$command.= " > " . $dumpfname;
system($command);
// zip the dump file
$zipfname = $dbname . "_" . date("Y-m-d_H-i-s").".zip";
$zip = new ZipArchive();
if($zip->open($zipfname,ZIPARCHIVE::CREATE))
{
$zip->addFile($dumpfname,$dumpfname);
$zip->close();
}
// read zip file and send it to standard output
if (file_exists($zipfname)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($zipfname));
flush();
readfile($zipfname);
exit;
}
?>
此代碼不需要可寫權(quán)限:
<?php
ob_start();
$username = "root";
$password = "";
$hostname = "localhost";
$dbname = "cars";
// if mysqldump is on the system path you do not need to specify the full path
// simply use "mysqldump --add-drop-table ..." in this case
$command = "C:\\xampp\\mysql\\bin\\mysqldump --add-drop-table --host=$hostname
--user=$username ";
if ($password)
$command.= "--password=". $password ." ";
$command.= $dbname;
system($command);
$dump = ob_get_contents();
ob_end_clean();
// send dump file to the output
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($dbname . "_" .
date("Y-m-d_H-i-s").".sql"));
flush();
echo $dump;
exit();]]>
?>
原文:http://webcheatsheet.com/php/how_to_create_a_dump_of_mysql_database_in_one_click.php