PDO:如果UPDATE:column和WHERE:column相同,则阻止值覆盖

时间:2018-05-07 18:47:59

标签: php mysql pdo

我有一个函数可以绑定/准备语句然后执行它:

function db_update ($table, $set, $where_col, $where_val)
{
    $s = "UPDATE `$table` SET ";
    foreach ($set as $k => $v)
        $s.= "$k = :".trim($k).", ";
    $s = trim($s, ', ');
    $s.= " WHERE `$where_col` = :$where_col";

    $binds = array();
    foreach ($set as $k => $v)
        $binds[':'.$k] = trim($v);
    $binds[':'.$where_col] = trim($where_val);

    return db_run($s, $binds);
}

基本上db_run执行您常用的PDO方法:

function db_run($stmt, $binds = array())
{
    // ...      
    $sth = $db->prepare($stmt);
    $sth->execute($binds);      
    // ...
}

样本用法A:

db_update('table', ['color' => 'red'], 'fruit', 'apple');

结果:

  • 准备:UPDATE table SET color = :color WHERE fruit = :fruit
  • 实际:UPDATE table SET color = 'red' WHERE fruit = 'apple'

这样运行得很好,但我的主要问题是如果用法如下:

样本用法B:

db_update('table', ['color' => 'red'], 'color', 'black');

结果:

  • 准备:UPDATE table SET color = :color WHERE color = :color
  • 实际:UPDATE table SET color = 'black' WHERE color = 'black'

我怎样才能做到这一点,实际结果如下:

UPDATE table SET color = 'red' WHERE color = 'black'

1 个答案:

答案 0 :(得分:3)

您获得该结果是因为您在查询中的两个地方(SET和WHERE)都使用了:color参数。因此,您的db_update()函数需要为WHERE子句使用不同的参数名称。

function db_update ($table, $set, $where_col, $where_val)
{
    $s = "UPDATE `$table` SET ";
    foreach ($set as $k => $v)
        $s.= "$k = :".trim($k).", ";
    $s = trim($s, ', ');
    $s.= " WHERE `$where_col` = :where_$where_col";

    $binds = array();
    foreach ($set as $k => $v)
        $binds[':'.$k] = trim($v);
    $binds[':where_'.$where_col] = trim($where_val);

    return db_run($s, $binds);
}

这应该会产生UPDATE table SET color = :color WHERE color = :where_color

的准备结果