2008/12/13

快速備份mysql

有些環境沒有好用的mysql管理工具,想要匯出資料備份就有些辛苦,將下面php程式放到網站上,設定好mysql連線,就可以很快產生備份檔了


//建立連線
$conn = mysql_connect(...);
//選擇database
mysql_select_db("database name", $conn);

//存放table名稱的陣列
$tables = array();
$res = mysql_query("show tables");
while($r = mysql_fetch_row($res)) {
array_push($tables, $r[0]);
}

foreach($tables as $table) {
//get table schema
$cond1 = "show create table $table";
$res1 = GetRs($cond1);
$r = mysql_fetch_assoc($res1);
echo $r['Create Table'].";<br/>";
mysql_free_result($res1);

//取得每筆資料
$cond2 = "select * from $table;";
$res2 = GetRs($cond2);
while($r = mysql_fetch_assoc($res2)) {
$fields = "";
$values = "";

foreach($r as $field => $value) {
$fields.= $field.",";
$values.= "'".addslashes($value)."',";
}
$fields = substr($fields, 0, strlen($fields)-1);
$values = substr($values, 0, strlen($values)-1);
echo "insert into $table($fields) values($values);<br/>";
mysql_free_result($res2);
}
}
mysql_close($conn);
exit(0);


ps.應該可以用吧。

沒有留言 :