带括号的 PDO 更新查询
PDO update query with brackets
我想执行这样的查询:
UPDATE users SET online_time = (online_time + 50) WHERE ID = 1
我有一个问题,因为 online_time 没有更新,它被 0 取代了。
在 mysqli 中一切正常。
这是我在数据库 class 中更新函数的代码(来自互联网,不是我的作品):
public function update($table, $data, $where)
{
ksort($data);
$fieldDetails = null;
foreach($data as $key => $value){
$fieldDetails .= "$key=:$key, ";
}
$fieldDetails = rtrim($fieldDetails, ', ');
$sth = $this->prepare("UPDATE $table SET $fieldDetails WHERE $where");
foreach ($data as $key => $value){
$sth->bindValue(":$key", $value);
}
$sth->execute();
}
和我正在尝试的代码 运行:
$set = ['online_time' => "(online_time + $t)"];
$where = 'ID = '. $id;
$this->db->update('users', $set, $where);
更新功能可能有问题,但我不知道是什么:/
您的更新功能的首要问题是它 prone to SQL injection。
是的,它不适合用这样的复杂表达式进行更新。
所以对于这个特定的查询,只需避免使用这个函数,运行 只是一个原始的准备语句
$sth = $db->prepare("UPDATE users SET online_time = online_time + ? WHERE ID = ?");
$sth->execute([$t, $id]);
我想执行这样的查询:
UPDATE users SET online_time = (online_time + 50) WHERE ID = 1
我有一个问题,因为 online_time 没有更新,它被 0 取代了。 在 mysqli 中一切正常。 这是我在数据库 class 中更新函数的代码(来自互联网,不是我的作品):
public function update($table, $data, $where)
{
ksort($data);
$fieldDetails = null;
foreach($data as $key => $value){
$fieldDetails .= "$key=:$key, ";
}
$fieldDetails = rtrim($fieldDetails, ', ');
$sth = $this->prepare("UPDATE $table SET $fieldDetails WHERE $where");
foreach ($data as $key => $value){
$sth->bindValue(":$key", $value);
}
$sth->execute();
}
和我正在尝试的代码 运行:
$set = ['online_time' => "(online_time + $t)"];
$where = 'ID = '. $id;
$this->db->update('users', $set, $where);
更新功能可能有问题,但我不知道是什么:/
您的更新功能的首要问题是它 prone to SQL injection。
是的,它不适合用这样的复杂表达式进行更新。
所以对于这个特定的查询,只需避免使用这个函数,运行 只是一个原始的准备语句
$sth = $db->prepare("UPDATE users SET online_time = online_time + ? WHERE ID = ?");
$sth->execute([$t, $id]);