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条)

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备