为什么这个MySQL语句语法错误?

时间:2013-12-10 18:17:21

标签: php mysql sql

我正在使用预准备语句处理传入的帖子数据,清理数组,并插入MySQL数据库。

这是提交之前的SQL语句:

INSERT INTO LoggedCarts (Bill-Address1,Bill-Address2,Bill-City,Bill-Company,Bill-Country,Bill-Email,Bill-Firstname,Bill-Lastname,Bill-Name,Bill-Phone,Bill-State,Bill-Zip,Card-Expiry,Card-Name,Card-Number,Comments,Date,ID,IP,Item-Code-1,Item-Count,Item-Description-1,Item-Id-1,Item-Quantity-1,Item-Taxable-1,Item-Thumb-1,Item-Unit-Price-1,Item-Url-1,Numeric-Time,Ship-Address1,Ship-Address2,Ship-City,Ship-Company,Ship-Country,Ship-Email,Ship-Firstname,Ship-Lastname,Ship-Name,Ship-Phone,Ship-State,Ship-Zip,Shipping,Space-Id,Store-Id,Store-Name,Tax-Charge,Total) VALUES ("Pineapple Highway","","Orange","","US United States","casedilla@hotmail.com","Bob","Dole","Bob Dole","9075554509","CA","97056","","Check","NumberTemporarilyUnavailable","","Tue Dec 10 16:55:11 2013 GMT","yhst-130408242826480-485","50.78.241.193","TERRALUX-TT-5","1","Terralux TT-5 LED Tactical Flashlight 650 Lumens Uses 2 x CR123 or 1 x 18650","terralux-tt-5","3","YES","","112.49","http://www.batteryjunction.com/terralux-tt-5.html","1386694511","Pineapple Highway","","Orange","","US United States","casedilla@hotmail.com","Bob","Dole","Bob Dole","9075554509","CA","97056","Air (3-5 days)","","yhst-130408242826480","BatteryJunction.com","0.00","337.47")

问题是,语法有什么问题?相同的代码也用于保存废弃购物车的不同表格,并且写得很好。

注意:正如下面所指出的,在列名中使用连字符是不受欢迎的,因为它需要在提交查询之前进行特殊准备。在这个例子中,我将列名称与传入的post数据键数组匹配。我本可以通过并清理关键数组,删除连字符,这可能是另一种解决方案。

总而言之,如下所示,对于此SQL语句失败原因的问题的正确解决方案是在列名中使用特殊字符(连字符),从而导致需要在列名称周围使用反引号(backtick =`where as apostrophe =')允许不间断地读取列名。

通过在PHPMyAdmin中测试原始语句来观察中断发生的位置:

#1064 - 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 '-Address1,Bill-Address2,Bill-City,Bill-Company,Bill-Country,Bill-Email,Bill-Firs' at line 1

确实给出了声明失败原因的线索。

感谢帮助人员!

3 个答案:

答案 0 :(得分:7)

您需要使用带反引号的特殊字符来转义列名。 -是一个特殊角色。使用

INSERT INTO LoggedCarts (`Bill-Address1`, ...

答案 1 :(得分:1)

如果这些字段名称确实包含减号,那么它们需要用反引号括起来:

`Bill-Address1`

答案 2 :(得分:-1)

尝试使用单引号插入字符串值。