程序备份数据库

<?php
header("Content-type:text/html;charset=utf-8");
$database = "thinksns_3_1";
$link = mysql_connect('localhost','root','123456') or die('连接失败');
mysql_select_db($database) or die('连接数据库失败');
//选择编码
mysql_query("set names utf8");
//1.获取所有的表
$rs = mysql_query("SHOW TABLES FROM $database");
$tableArray = array();
while ($row = mysql_fetch_row($rs)) {
$tableArray[] = $row[0];
}
mysql_free_result($rs);


//2.配置文件名
$to_file_name ="./".time().".sql";
$info ="/*".date('Y-m-d')."导出数据*/\r\n";
file_put_contents($to_file_name,$info,FILE_APPEND);


//3.循环表
foreach($tableArray as $val){
$sql = "show create table ".$val;
$res = mysql_query($sql,$link);
$row = mysql_fetch_array($res);
$info = "/*-- Table structure for `".$val."`*/\r\n";
$info .= "DROP TABLE IF EXISTS `".$val."`;\r\n";
$sqlStr = $info.$row[1].";\r\n\r\n";
//追加到文件
file_put_contents($to_file_name,$sqlStr,FILE_APPEND);
//释放资源
mysql_free_result($res);


$sql = "select * from ".$val;
$res = mysql_query($sql,$link);
//如果表中没有数据,则继续下一张表
if(mysql_num_rows($res)<1) continue;
//
$info = "/*-- Records for `".$val."`*/\r\n";
file_put_contents($to_file_name,$info,FILE_APPEND);
//读取数据
while($row = mysql_fetch_row($res)){
$sqlStr = "INSERT INTO `".$val."` VALUES (";
foreach($row as $zd){
$sqlStr .= "'".$zd."', ";
}
//去掉最后一个逗号和空格
$sqlStr = substr($sqlStr,0,strlen($sqlStr)-2);
$sqlStr .= ");\r\n";
file_put_contents($to_file_name,$sqlStr,FILE_APPEND);
}
//释放资源
mysql_free_result($res);
file_put_contents($to_file_name,"\r\n",FILE_APPEND);
}


header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
header("Accept-Length: ".filesize($to_file_name));
header("Content-Disposition: attachment; filename=" . $to_file_name);
readfile($to_file_name);
echo "数据全部到处";

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。