第1行的MySql语法错误

时间:2012-02-06 18:30:59

标签: php mysql mysqldump

我制作了一个备份脚本,它输出一个能够恢复数据库的.sql文件。在恢复数据库时,MySql告诉我语法有问题。

  

您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   靠近')ENGINE = MyISAM DEFAULT CHARSET =第1行的latin1'

   DROP TABLE category; 

CREATE TABLE `category` ( 
`cat_id` varchar(4) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, 
`cat_name` varchar(15) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, 
PRIMARY KEY (`cat_id`) 
) ENGINE=MyISAM DEFAULT CHARSET=latin1; 

使用此脚本

读取.sql文件
    // Read in entire file
$sql_commands_array = file($backup_file);

$file = fopen($backup_file, "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
  {
  echo fgets($file). "<br />";
  }
fclose($file);

// Loop through each line
foreach ($sql_commands_array as $current_command)
{
    //echo $current_command."test";

    // Add this line to the current segment
    $current_query .= $current_command;
    // If it has a semicolon at the end, it's the end of the query
    if (substr(trim($current_command), -1, 1) == ';')
    {
        // Perform the query
        mysql_query($current_query) or print('Error Updating DB'.mysql_error().'<br />');
        // Reset temp variable to empty
    }

    $current_query = '';
}

有关如何解决此问题的任何建议。 CREATE TABLE输出是使用mysql_query('SHOW CREATE TABLE'。$ table)

创建的。

2 个答案:

答案 0 :(得分:2)

最佳解决方案是:

`mysql < $backup_file`

恢复mysqldump文件要比你想象的要复杂得多。例如,分号可以出现在注释,字符串文字或内部CREATE PROCEDURE语句中,而不是SQL语句的结尾。您的PHP代码无法处理这些情况。

如果您准备限制所支持的语句类型,则可以编写一个简单的PHP函数来从文件执行SQL语句。支持所有有效的SQL脚本需要几个月的工作,并且需要一个真正的解析器,而不是substr()

答案 1 :(得分:0)

您应该清空$current_query块中的if (substr(trim($current_command), -1, 1) == ';')。但相反,你在每次迭代中都这样做。结果是,您要将备份文件中的行发送到mysql_query而不是完整查询。