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

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码