mysql 导出并压缩_一键导出MySQL数据库并zip压缩的php代码

有时候,你的用户要求添加一个选项,导出整个数据库到一个SQL文件。虽然phpMyAdmin,以及Navicat有这个功能,但你的用户想要更简单点怎么办?

以下是如何一键导出MySQL数据库的php代码。

新建一个名为backup.php的文件,复制粘贴以下代码,然后编辑数据库连接设置和mysqldump的路径。有必要的话,你还可以添加一个backup.php超链接到你的程序里:

导出整个数据库

请注意,第一个php代码执行的时候,会导出zip压缩后的sql文件,所以此代码所在文件夹需要可写的权限。

如果你没有写的权限,请使用第二个php代码,缺点是导出的sql文件不会被zip压缩。

此代码需要可写权限:

$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;

}

?>

此代码不需要可写权限:

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

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值