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.
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.
You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).
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.
If you use php to connect to mysql you can use mysql_insert_id() to point to last inserted id. Save this answer.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With