我正在尝试创建一个脚本来创建一个mysql数据库的转储,但是,我无法让它工作。以下是我正在起诉的代码。
$file = 'backup_'.substr(md5(TIME_NOW), 0, 10).random_str(30);
header('Content-Type: text/x-sql');
header('Content-Disposition: attachment; filename="'.$file.'.sql"');
// process backup
$time = date('dS F Y \a\t H:i', TIME_NOW);
$header = "-- Database Backup\n-- Generated: {$time}\n-- -------------------------------------\n\n";
$contents = $header;
$table_selects = array();
$table_list = $db->list_tables($config['database']['database']);
foreach($table_list as $id => $table_name)
{
$table_selects[$table_name] = $table_name;
}
$field_list = array();
$fields_array = $db->show_fields_from($table_name);
foreach($fields_array as $field)
{
$field_list[] = $field['Field'];
}
$query = $db->simple_select($table);
while($row = $db->fetch_array($query))
{
$insert = "INSERT INTO {$table} ($fields) VALUES (";
$comma = '';
foreach($field_list as $field)
{
if(!isset($row[$field]) || is_null($row[$field]))
{
$insert .= $comma."NULL";
}
else
{
$insert .= $comma."'".$db->escape_string($row[$field])."'";
}
$comma = ',';
}
$insert .= ");\n";
$contents .= $insert;
clear_overflow($fp, $contents);
}
但它不起作用......而且我知道我的代码有些错误,例如要选择哪些表(我想选择所有表)。
答案 0 :(得分:2)
下面可能是一种更简单的备份数据库的方法,而无需处理所有信息。由于它是一个MySQL语句,它可能也会快速运行。
从这里:
http://www.noupe.com/how-tos/10-ways-to-automatically-manually-backup-mysql-database.html
<?php
include 'config.php';
include 'opendb.php';
$tableName = 'mypet';
$backupFile = 'backup/mypet.sql';
$query = "SELECT * INTO OUTFILE '$backupFile' FROM $tableName";
$result = mysql_query($query);
include 'closedb.php';
?>