phpmysqlpdolastinsertid

Can I get INSERT/UPDATE id with single request?


I have the following code:

$put_tag_rq = $DBH->prepare( "
  INSERT INTO `tags`
  SET
    `name` = :name
  ON DUPLICATE KEY UPDATE
    `id` = `id`
" );
$put_tag_rq->execute( array(
  'name' => $tag,
) );
$tag_id = $DBH->lastInsertId();
echo "***********Last insert ID = $tag_id<br>";

Please note that the name is also the tab's key.

This code works fine if the inserting name tag is not yet presented in the table. But lastInsertId() returns 0 if name already there.

Of course I could do two requests: first to check if the name tag already presented in the tab (and obtain its ID) and the second to insert the name is already presented in the tab.

But I think that it should be simpler. Isn't it?


Solution

  • This is the MySQL that you're looking for: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

    And more info on how to do it in php: PHP MYSQL UPDATE if Exist or INSERT if not?