PHP MySQL导出备份脚本
参考了别人的脚本,稍微修改了一下,目前还没发现bug。
如有问题请评论区告诉我。
$sqlInfo = array(
'host' => 'localhost',
'port' => '3306',
'username' => 'root', // 只是示例
'password' => '1234', // 只是示例
'database' => '',
'charset' => 'utf8mb4'
);
function sqlBackUp($sqlInfo, $filename) {
$link = mysqli_connect($sqlInfo['host'], $sqlInfo['username'], $sqlInfo['password'], $sqlInfo['database'], $sqlInfo['port']);
mysqli_options($link, MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
mysqli_query($link, "set names ".$sqlInfo['charset']);
$tables = mysqli_query($link, 'SHOW TABLES FROM '.$sqlInfo['database'].'');
$tabList = array();
while ($row = mysqli_fetch_row($tables)) {
$tabList[] = $row[0];
}
$mysql = '';
foreach ($tabList as $val) {
$sql = "show create table ".$val;
$res = mysqli_query($link, $sql);
$row = mysqli_fetch_array($res);
$info = "DROP TABLE IF EXISTS `".$val."`;\r\n";
$mysql .= $info.$row[1].";\r\n\r\n";
mysqli_free_result($res);
}
foreach ($tabList as $val) {
$sql = "select * from ".$val;
$res = mysqli_query($link, $sql);
if (mysqli_num_rows($res) < 1) {
continue;
}
while ($row = mysqli_fetch_row($res)) {
$mysql .= "INSERT INTO `".$val."` VALUES (";
foreach ($row as $zd) {
if (gettype($zd) == 'NULL') {
$mysql .= "NULL, ";
} else if (gettype($zd) == 'string') {
$mysql .= "'".addslashes($zd)."', ";
} else {
$mysql .= $zd.", ";
}
}
$mysql = substr($mysql, 0, strlen($mysql)-2);
$mysql .= ");\r\n";
}
mysqli_free_result($res);
$mysql .= "\r\n";
}
mysqli_close($link);
$fp = fopen($filename, 'w');
fputs($fp, $mysql);
fclose($fp);
}