dopuzf0898 2016-07-28 07:28
浏览 180
已采纳

MySQL PDO - ON DUPLICATE KEY UPDATE在没有更改的情况下返回false吗?

I'm saving data from an API, and running a ON DUPLICATE KEY UPDATE. The thing is that it saved without errors on the first go around, but on consecutive runs it returns false, with the following errorInfo()

Array ( [0] => 00000 [1] => [2] => ) 

I ran the SQL manually in phpMyAdmin, and it works (0 rows inserted), does this return false when no changes are made?

My apologies for horrible code here, the PDO instance is saved as $this->db (I'm saving some JSON in this function, so the usual prepare escaping was erroring on the :, hence the "make-due" solution under)

public function update($table, $valuePairs)
{
    $columns = '';
    $values = '';
    $updates = '';
    foreach ($valuePairs as $column => $value)
    {
        if($value !== null and $value !== '') {
            $columns .= '`'.$column.'`, ';
            $values .= $this->db->quote($value).', ';
            $updates .= '`'.$column.'` = VALUES(`'.$column.'`), ';
        }
    }
    $columns = rtrim($columns, ', ');
    $values = rtrim($values, ', ');
    $updates = rtrim($updates, ', ');

    $sql = 'INSERT INTO '.$table.' ('.$columns.')
            VALUES ('.$values.')
            ON DUPLICATE KEY UPDATE '.$updates;

    $result = $this->db->exec($sql);
    if(!$result)
    {
        print_r($this->db->errorInfo());
        echo '<br><br>';
    }

    return $result;
}
  • 写回答

2条回答 默认 最新

  • dougaimian1143 2016-07-28 07:58
    关注

    Let's look carefully at PDO::exec() manual page:

    Return Values

    PDO::exec() returns the number of rows that were modified or deleted by the SQL statement you issued. If no rows were affected, PDO::exec() returns 0.

    Warning

    This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

    But your code does not make any distinction between zero and false:

    if(!$result)
    {
        print_r($this->db->errorInfo());
        echo '<br><br>';
    }
    

    You probably want this:

    if ($result===false)
    {
        print_r($this->db->errorInfo());
        echo '<br><br>';
    }
    

    Getting zero rows updated when you run the statement twice is the expected behaviour because MySQL won't update a row if values do not change.

    I particularly prefer to forget about error handling and configure PDO to just throw exceptions.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度