SQL错误:1064您的SQL语法中有错误

时间:2018-06-13 15:03:13

标签: php mysql sql mysqli prepared-statement

我有一个名为用户的表:

    ____         ____            __________        _____________
   |    |       |     |          |         |       |           |
   | 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 = ?'

我使用的方法因为我不知道选择了哪种情况,所以我依赖于名字。

1 个答案:

答案 0 :(得分:0)

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

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;