如何修复MySQL数据库的SQL语法错误?

时间:2015-04-18 05:53:51

标签: php mysql

我想通过Web表单界面将.csv文件数据上传到MySQL表。在搜索脚本之后,我找到了一个来完成这项工作,但它在执行期间给出了SQL语法错误。在这里,我现在给出了特定的代码片段,但如果需要,我会提供完整的代码。

            if($this->table_exists)
            {
              $sql = "LOAD DATA INFILE '".@mysql_escape_string($this->file_name).
                     "' INTO TABLE '".$this->table_name.
                     "' FIELDS TERMINATED BY '".@mysql_escape_string($this->field_separate_char).
                     "' OPTIONALLY ENCLOSED BY '".@mysql_escape_string($this->field_enclose_char).
                     "' ESCAPED BY '".@mysql_escape_string($this->field_escape_char).
                     "' ".
                     ($this->use_csv_header ? " IGNORE 1 LINES " : "")
                     ."('".implode("','", $this->arr_csv_columns)."')";
              $res = @mysql_query($sql);
              $this->error = mysql_error();
            }

在执行期间,它抛出以下错误:

错误

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''temp_18_04_2015_05_44_00' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\\' ' at line 1

gererated SQL命令如下

LOAD DATA INFILE '/tmp/phpFzT3qc' 
INTO TABLE 'temp_18_04_2015_06_06_37' 
FIELDS TERMINATED BY ',' 
OPTIONALLY ENCLOSED BY '\\' 
ESCAPED BY '\\' 
IGNORE 1 LINES ('SLNO','NAME')

我是新手程序员,所以我无法得到错误......

1 个答案:

答案 0 :(得分:2)

我认为您必须删除表名称旁边的单引号:

$sql = "LOAD DATA INFILE '".@mysql_escape_string($this->file_name).
                     "' INTO TABLE ".$this->table_name.
                     " FIELDS TERMINATED BY '".@mysql_escape_string($this->field_separate_char).
                     "' OPTIONALLY ENCLOSED BY '".@mysql_escape_string($this->field_enclose_char).
                     "' ESCAPED BY '".@mysql_escape_string($this->field_escape_char).
                     "' ".
                     ($this->use_csv_header ? " IGNORE 1 LINES " : "")
                     ."('".implode("','", $this->arr_csv_columns)."')";

如果您使用单个qoutes,则它是一个字符串而不是表名。要转义表名,你必须使用反引号。

有关LOAD DATA INFILE语法的详细信息,请参阅documentation