如何一鍵導出MySQL數據庫

有時候,你的用戶要求添加一個選項,導出整個數據庫到一個SQL文件。雖然phpMyAdmin,以及Navicat有這個功能,但你的用戶想要更簡單點怎麼辦?

以下是如何一鍵導出MySQL數據庫的php代碼。

新建一個名爲backup.php的文件,複製粘貼以下代碼,然後編輯數據庫連接設置和mysqldump的路徑。有必要的話,你還可以添加一個backup.php超鏈接到你的程序裏:

<A href="backup.php">導出整個數據庫</A>


 

請注意,第一個php代碼執行的時候,會導出zip壓縮後的sql文件,所以此代碼所在文件夾需要可寫的權限。
如果你沒有寫的權限,請使用第二個php代碼,缺點是導出的sql文件不會被zip壓縮。

此代碼需要可寫權限:

<?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; 
} 
?> 


此代碼不需要可寫權限:

<?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();]]> 
?>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章