|
/** 備份資料庫 產生.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;
}
?> |