/** 备份数据库 生成.sql文件
* @param $browseinfo String 浏览器版本
* return $browseinfo
*/
function createsql(){
//创建个日期
$timer1 = time();
$path = "my_sql/";
$content =gettables();
$filename = $path.$timer1.".sql";
//先判断文件夹在不在
if(!file_exists($path)){
//如果不存在生成这个目录,0777表示最大的读写权限
if(mkdir($path,0777)){
//echo"新建立目录";
}
}
//判断文件是否存在
if(!file_exists($filename)){
//如果文件不存在,则创建文件
@fopen($filename,"w");
//判断文件是否可写
if(is_writable($filename)){
//打开文件以添加方式即"a"方式打开文件流
if(!$handle = fopen($filename,"a")){
echo"文件不可打开";
exit();
}
if(!fwrite($handle,$content)){
echo"文件不可写";
exit();
}
//关闭文件流
fclose($handle);
echo "生成文件并保存首次内容";
}else {
echo"文件$filename不可写";
}
}else{
if(is_writable($filename)){
//以添加方式打开文件流
if(!$handle = fopen($filename,"a")){
echo"文件不可打开";
exit();
}
fclose($handle);
}else{
echo "文件$filename不可写";
}
}
}
/**
* 获得数据库中的表名
* return $str 循环生成数据库建表和插入值的sql语句
*/
function gettables(){
$mysqli = new mysqli("localhost","root","","bbs");
$str = '';
if ($result = $mysqli->query("SHOW TABLES")) {
while($row = $result->fetch_row()){
$str.= data2sql($row[0])." ";
}
$mysqli->close();
return $str;
}
}
/**
* 获得数据库中的表结构和值
* return $tabledump 返回一个表中的结构和值的sql语句
*/
function data2sql($table){
$mysqli = new mysqli("localhost","root","","bbs");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %sn", mysqli_connect_error());
exit();
}
$tabledump = "DROP TABLE IF EXISTS $table;n";
$result = $mysqli->query("SHOW CREATE TABLE $table");
$create = $result->fetch_row();
$tabledump .= $create[1].";nn";
$rows = $mysqli->query("SELECT * FROM $table");
$numfields = $rows->num_rows;
while ($row = $rows->fetch_row()){
$comma = "";
$tabledump .= "INSERT INTO $table VALUES(";
for($i = 0; $i < $numfields; $i++)
{
$tabledump .= $comma."'".mysql_escape_strin
g($row[$i])."'";
$comma = ",";
}
$tabledump .= ");n";
}
$tabledump .= "n";
return $tabledump;
}
?>
|