【问题标题】:PHP : You have an error in your SQL syntax check the manualPHP:您的 SQL 语法有错误,请查看手册
【发布时间】:2016-07-31 06:57:44
【问题描述】:

我正在尝试通过提交表单来插入数据,这是我得到的错误

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 'desc,refno,quantity,imgname, image) 
VALUES('name','Some desc ', '123','123' at line 1

下面是我的sql查询

$query= mysqli_query($connect,
     "INSERT INTO products(name,desc,refno,quantity) 
      VALUES('$names','$productdesc', '$refno','$quanitity')");

以下是所附的 db 截图

如果我打电话给print_r 这就是我得到的

Array
(
    [name] => name
    [refno] => 123
    [quantity] => 123456
    [description] => Some desc 
    [submit] => Add Product
)

【问题讨论】:

  • DESC 是保留字,使用反引号,`desc`
  • 或者,最好不要使用 desc

标签: php mysql sql mysqli syntax-error


【解决方案1】:

因为desc是一个保留字,你需要把它放在反引号之间,告诉MySQL这是一个名字而不是order by中使用的desc

$query= mysqli_query($connect,
    "INSERT INTO products(`name`,`desc`,`refno`,`quantity`) 
     VALUES('$names','$productdesc', '$refno','$quanitity')");

您的情况是,最好总是在列名或表名等内容周围加上反引号,以确保即使某个单词突然被保留,您的代码也不会中断。

【讨论】:

    【解决方案2】:

    desc 是保留字。如果您可以控制架构,我建议您将该列重命名为非保留字,例如 description。如果这不可行或不可行,您可以通过用反引号括起来来转义列名:

    $query= mysqli_query($connect,
                         "INSERT INTO products(name,`desc`,refno,quantity) 
                         VALUES('$names','$productdesc', '$refno','$quanitity')");
    

    旁注:
    在 SQL 语句中使用字符串操作会使您的代码容易受到 SQL 注入攻击。您应该考虑改用prepared statements

    【讨论】:

      猜你喜欢
      • 2016-06-29
      • 2019-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-05
      • 2020-05-07
      • 2018-09-29
      相关资源
      最近更新 更多