Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does lastInsertId() work for tables without auto-incremented fields?

Tags:

php

mysql

How does lastInsertId() work for tables that do not have an auto-incremented field? What about tables where the primary key is made up of 2 fields?

(I'm working with MySQL)

like image 555
JDelage Avatar asked Sep 24 '12 23:09

JDelage


2 Answers

In both cases above it will return 0.

When using an auto_increment column, it will return the last INSERT ID even if it was specified (i.e. the auto increment was not used).

That is to say you should only use lastInsertId when using auto increment. It doesn't really make sense to use it otherwise since you would have to know the keys ahead of time anyway..

like image 135
Explosion Pills Avatar answered Sep 21 '22 15:09

Explosion Pills


I don't think it does as it is a function specifically designed to be used to retrieve the value of an AUTO_INCREMENT field.

http://php.net/manual/en/function.mysql-insert-id.php

mysql_insert_id

Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).

This type of thing is easy enough to test - have you tried it to see what happens?

like image 20
Dutchie432 Avatar answered Sep 17 '22 15:09

Dutchie432