我正在尝试使用以下代码从http://www.a2zwebhelp.com/php-script-to-import-mysql-database恢复数据库但我收到"错误:查询是空的"我哪里做错了?
注。从phpmyadmin导入SQL文件可以达到这个目的,但是使用这个不能工作。
<?php
include 'connect.php';
$filename = 'DB_Backups/db-backup-08-04-14-08-39-16.sql';
$templine = '';
$lines = file($filename); //Read entire file
foreach($lines as $line){
if(substr($line, 0, 2) == '--' || $line == '') //Skip all comments
$templine.=$line;
if(substr(trim($line), -1, 1) == ';'){
mysql_query($templine) or print('Error: '.mysql_error().'<br>');
$templine = '';
}
}
?>
首先,这部分代码没有跳过注释,它实际上是将它们添加到您的$templine
:
if(substr($line, 0, 2) == '--' || $line == '') //Skip all comments
$templine.=$line;
其次,这里您尝试使用上面分配的$templine
执行查询(如果它曾经被分配,或者''
),而实际上您想使用$line
执行查询:
if(substr(trim($line), -1, 1) == ';'){
mysql_query($templine) or print('Error: '.mysql_error().'<br>');
所以,基本上这应该能更好地工作:
foreach($lines as $line){
if(substr($line, 0, 2) == '--' || $line == '') //Skip all comments
continue;
if(substr(trim($line), -1, 1) == ';'){
mysql_query(trim($line)) or print('Error: '.mysql_error().'in ' . $line . '<br>');
}
}
一个小小的改进,它的工作:)@ favoretti谢谢你的提示。
<?php
// Name of the file
$filename = 'DB_Backups/'.$name;
// Temporary variable, used to store current query
$templine = '';
// Read in entire file
$lines = file($filename);
// Loop through each line
foreach ($lines as $line)
{
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '')
continue;
// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';')
{
// Perform the query
mysql_query($templine) or print('Error performing query ''<strong>' . $templine . ''': ' . mysql_error() . '<br /><br />');
// Reset temp variable to empty
$templine = '';
}
}
?>