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

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?

图片转代码服务由CSDN问答提供 功能建议

我有以下代码:

  $ add_rq = $  DBH->准备('INSERT INTO`table`SET`URL` =:url ON DUPLICATE KEY UPDATE`url` =`url`'); 
if($ add_rq-> execute(['url'=>  $ url]))
 echo“已添加(id:”。$ DBH-> lastInsertId()。“)”; 
else 
 echo“未添加”; 
   
  
 

如果 ON DUPLICATE KEY UPDATE 语句中的 url 已经存在,那么 execute()的返回值始终是 TRUE 。 但是,在这种情况下, lastInsertId()为零。 我可以使用它作为插入重复的指示,或者我可以在插入之前再对DB进行一次查询,但这两种方法对我来说都很糟糕。

有没有更好的方法?< / p>

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题