douyong6589 2014-11-20 08:35
浏览 260
已采纳

PHP的PDO编写INSERT语句:我能否定义插入是否成功?

I have the following code:

$add_rq = $DBH->prepare('INSERT INTO `table` SET `url` = :url ON DUPLICATE KEY UPDATE `url`=`url`');
if($add_rq->execute(['url' => $url]))
  echo "Added (id: ".$DBH->lastInsertId().")";
else
  echo "Not added";

If the inserting url already exist in the table the ON DUPLICATE KEY UPDATE statement working but the return value of the execute() is always TRUE. However lastInsertId() is zero in this case. I COULD use this as the indication of the insertion duplication or I could do one more query to DB prior to the insert but both approaches looks bad to me.

Is there any better way?

  • 写回答

2条回答 默认 最新

  • dongting7352 2014-11-20 08:41
    关注

    You can use $add_rq->rowCount(). According to a comment in the documentation, it will return 1 if a new row was inserted, 2 if an existing row was updated. But apparently that's wrong, it returns 0 if a row was updated.

    execute() only returns false if it fails because of an error.

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

报告相同问题?