我有一个名为用户的表:
____ ____ __________ _____________
| | | | | | | |
| id | | name| |firstCon | | secondCon |
|____| |_____| |________ | |___________|
1 john true false
2 mark false false
我想使用firstCon
或secondCon
更改true
和false
值。
所以我使用以下查询:
$sql = "UPDATE users SET ? = ? WHERE name = ?";
$query->bind_param($condition, $value, $name);
其中$condition
为firstCon
或secondCon
,$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 = ?'
我使用的方法因为我不知道选择了哪种情况,所以我依赖于名字。
答案 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;