首页 > 解决方案 > SQL 错误:1064 您的 SQL 语法有错误

问题描述

我有一个名为 users 的表:

    ____         ____            __________        _____________
   |    |       |     |          |         |       |           |
   | id |       | name|          |firstCon |       | secondCon |
   |____|       |_____|          |________ |       |___________|

     1           john               true               false

     2           mark               false              false

我想用or更改firstConandsecondCon值。truefalse

所以我使用以下查询:

$sql = "UPDATE users SET ? = ? WHERE name = ?";
$query->bind_param($condition, $value, $name);

其中or , = ,$condition是用户名。firstConsecondCon$valuetrue/false$name

我得到那个错误:

1064 You have an error in your SQL syntax; 
check the manual that corresponds to your MariaDB server version 
for the right syntax to use near '? = ? WHERE name = ?'

我正在使用该方法,因为我不知道选择了哪个条件,所以我取决于名称。

标签: phpmysqlsqlmysqliprepared-statement

解决方案


您不能将列名(或其他标识符)作为参数传递。这是另一种方法,不需要修改查询字符串:

UPDATE users 
    SET firstcon = (case when ? = 'firstcon' then ? else firstcon end),
        secondcon = (case when ? = 'secondcon' then ? else secondcon end)
    WHERE name = ?;

注意:这有更多的占位符。如果将参数作为命名参数传递可能会更简单:

UPDATE users 
    SET firstcon = (case when :which = 'firstcon' then :value else firstcon end),
        secondcon = (case when :which = 'secondcon' then :value else secondcon end)
    WHERE name = :name;

推荐阅读