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?
You can use
$add_rq->rowCount(). According to a comment in the documentation, it will return1if a new row was inserted,2if an existing row was updated. But apparently that's wrong, it returns0if a row was updated.execute()only returns false if it fails because of an error.