当我不用`字符包装表和列时,为什么我的查询失败?

时间:2013-05-25 07:15:37

标签: php mysqli

希望一些老圣人可以对这一点有所了解。我很困惑(很容易)。

当我准备我的SQL语句时(在表和列名上使用`,这里没有显示输出?)...

$sql = "INSERT INTO `order` (`orderid`, `username`, `payer_email`, `purchase_str`, `mc_gross`, `tnx_id`, `status`) VALUES (default,'$user','$useremail','$purchase_str','$mc_gross','46737264646','pending')";

$result = mysqli_query ( $cxn, $sql ) or die ( "Query died: fusername" );

...它成功插入一行。

但是,当我使用没有单引号或'在表和列名称上,而不是`它失败时出现mysql错误,即

$sql = "INSERT INTO order (orderid,username,payer_email,purchase_str,mc_gross,tnx_id,status) VALUES (default,'$user','$useremail','$purchase_str','$mc_gross','46737264646','pending')";

$result = mysqli_query ( $cxn, $sql ) or die ( "Query died: fusername" );

错误:

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 'order (orderid, username, payer_email, purchase_str, mc_gross, tnx_id, status) V' at line 1

OR

$sql = "INSERT INTO 'order' ('orderid', 'username', 'payer_email', 'purchase_str', 'mc_gross', 'tnx_id', 'status') VALUES (default,'$user','$useremail','$purchase_str','$mc_gross','','pending')";

$result = mysqli_query ( $cxn, $sql ) or die ( "Query died: fusername" );

错误:

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 ''order' ('orderid', 'username', 'payer_email', 'purchase_str', 'mc_gross', 'tnx_' at line 1

我有另一个插入查询,而不使用表格和列名称上的“或”,但工作正常,即

$sql = "INSERT INTO user (username,password,created,email,firstname,lastname,dob,gender,house,street,area,city,county,postcode,country,skype,proofread) 
          VALUES ('$updatedb[username]','$hash',NOW(),'$updatedb[email]','$updatedb[firstname]','$updatedb[lastname]','$updatedb[dob]','$updatedb[gender]',
                  '$updatedb[house]','$updatedb[street]','$updatedb[area]','$updatedb[city]','$updatedb[county]','$updatedb[postcode]','$updatedb[country]',
                  '$updatedb[skype]','$updatedb[proofread]')";

非常非常困惑。任何指针都将非常感激。一路平安。

2 个答案:

答案 0 :(得分:3)

因为 status order是mysql中的保留字,你需要使用反引号`来转义它而不是单引号'

所以你的查询会看起来:

INSERT INTO
`order` (
`orderid`, `username`, `payer_email`, `purchase_str`, `mc_gross`, `tnx_id`, `status`
)
VALUES (
default,'$user','$useremail','$purchase_str','$mc_gross','','pending'
)

您可以找到reserved words here

的列表

注意:转义表名和列名是一个好习惯,因为很难记住所有保留字。

答案 1 :(得分:1)

单词order和单词status是SQL语句,因此您必须明确告诉MySQL它是表的名称,而不是MySQL的命令。详细了解order命令here