Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO lastInsertId() returns 0 when using on duplicate key update?

Tags:

php

mysql

pdo

I've got a query like the following:

$a = $members->prepare("insert into a(name) values(:name) 
                            on duplicate key update name = :name");

Then when I do:

$insert_id = $a->lastInsertId()

If the query successfully inserted a row, it will return the insert id as expected, if it updated a row, it will also return the updated row id as expected (sort of). But if it neither inserted or updated anything because everything was the same, then it just returns 0.

I guess this is pretty logical default behaviour, but is there a way to change it so that it can return the id of the row it attempted to update, like it does when it actually changes something in the row.

Thanks.

like image 402
John Smith Avatar asked Mar 12 '13 22:03

John Smith


People also ask

What is lastInsertId?

Definition and Usage. The LAST_INSERT_ID() function returns the AUTO_INCREMENT id of the last row that has been inserted or updated in a table.

How can I get last insert ID in PDO?

You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).

How fetch data from database in PHP and display PDO?

Fetch data from a result set by calling one of the following fetch methods: To return a single row from a result set as an array or object, call the PDOStatement::fetch method. To return all of the rows from the result set as an array of arrays or objects, call the PDOStatement::fetchAll method.

How can I get last inserted record in mysql using PHP?

If you use php to connect to mysql you can use mysql_insert_id() to point to last inserted id. Save this answer.


2 Answers

There are many places to find the answer on this, but the specificity to PDO may be hindering your search results...

First, make sure to add id=LAST_INSERT_ID(id) to the ON DUPLICATE clause, as noted at the bottom of the DOCS. The id in this case is the column name of your primary key (so in your case it may/may not be titled id).

Also, you may have to specify a sequence object argument to ->lastInsertId() to make it work. I've encountered that problem in certain circumstances before.

like image 110
anson Avatar answered Oct 25 '22 00:10

anson


No, because there is no row it 'attempts' to update. Also, be careful: if you had another insert query before that in the same session, you could get value of LAST_INSERT_ID() from that previous query.

like image 32
Mchl Avatar answered Oct 24 '22 23:10

Mchl