pdo:如果update:column和where:column相同,则防止值覆盖

vh0rcniy  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(378)

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

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'

r3i60tvu

r3i60tvu1#

你得到这个结果是因为你在使用 :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

相关问题