SQL Error :1064 You have an error in your SQL syntax

SQL Error :1064 You have an error in your SQL syntax

我有一个 Table 这样的用户:

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

     1           john               true               false

     2           mark               false              false

我想将 firstConsecondCon 值更改为 truefalse

所以我正在使用以下查询:

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

其中 $conditionfirstConsecondCon$value = true/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 = ?'

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

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

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;