<?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 "数据全部到处";
时间: 2024-12-26 04:10:36