我有下面的脚本无法正常工作:
脚本应该为我的数据库创建一个sql文件并直接输出文件而不是保存它,而是我得到一个空文件!!
请帮忙!
// Connect to database
$connection = @mysql_connect($server, $dbusername, $dbpassword) or die(mysql_error());
$db = @mysql_select_db($db_name,$connection) or die(mysql_error());
//get all of the tables
$tables = array();
$result = mysql_query('SHOW TABLES');
while($row = mysql_fetch_row($result))
{
$tables[] = $row[0];
}
//cycle through
foreach($tables as $table)
{
$result = mysql_query('SELECT * FROM '.$table);
$num_fields = mysql_num_fields($result);
$return.= 'DROP TABLE '.$table.';';
$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
$return.= "\n\n".$row2[1].";\n\n";
for ($i = 0; $i < $num_fields; $i++)
{
while($row = mysql_fetch_row($result))
{
$return.= 'INSERT INTO '.$table.' VALUES(';
for($j=0; $j<$num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace("\n","\\n",$row[$j]);
if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
if ($j<($num_fields-1)) { $return.= ','; }
}
$return.= ");\n";
}
}
$return.="\n\n\n";
}
$FileName = $db_name . '_' . date("d-m-y") . '.sql';
header('Content-Type: application/sql');
header("Content-length: " . filesize($NewFile));
header('Content-Disposition: attachment; filename="' . $FileName . '"');
echo $return;
exit();
更新#1:我不能使用mysqldump,因为我在共享主机上,而且shell exec()是禁用的
答案 0 :(得分:0)
只需环绕mysqldump:
<?=shell_exec("mysqldump -h $server -u $dbusername -p$dbpassword $db_name");?>
请注意,您应该使用escapeshellarg()
转义命令的变量项,但为简洁起见,我省略了它。