dongzhi6905 2018-05-07 18:47
浏览 57
已采纳

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

I've a function that binds/prepares the statement then execute it:

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);
}

Basically db_run does your usual PDO methods:

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

Sample usage A:

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

Result:

  • Prepared: UPDATE table SET color = :color WHERE fruit = :fruit
  • Actual: UPDATE table SET color = 'red' WHERE fruit = 'apple'

This runs just fine, but my main issue is what if the usage is like this:

Sample usage B:

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

Result:

  • Prepared: UPDATE table SET color = :color WHERE color = :color
  • Actual: UPDATE table SET color = 'black' WHERE color = 'black'

How can I make it so the actual result is:

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

  • 写回答

1条回答 默认 最新

  • douhe1864 2018-05-07 19:02
    关注

    You're getting that result because you're using the :color parameter in both places (the SET and the WHERE) in your query. So your db_update() function needs to use a different parameter name for the WHERE clause.

    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);
    }
    

    This should result in a prepared result of UPDATE table SET color = :color WHERE color = :where_color

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题