I have the following code. The mysqli_insert_id() (in this case \"$last_row\"), which is supposed to return the last row of the table, is always returning 0. Why is it so?
Another gotcha with this function -- if you're doing:
INSERT INTO table (col1, col2) VALUES (1, 2) ON DUPLICATE KEY UPDATE col2=3
and insert doesn't happen because of a duplicate key and for the UPDATE
, like in my case, if col2
was already set to 3
, then mysqli_insert_id
will also return 0.
mysqli_insert_id
does not return the ID of the last row of the table. From the docs, it:
...returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute. If the last query wasn't an
INSERT
orUPDATE
statement or if the modified table does not have a column with theAUTO_INCREMENT
attribute, this function will return zero.
(My emphasis)
That is, if you were to run it immediately after an insert that auto-generated an ID, on the same connection you did the insert with, it would return the ID generated for that insert.
This is illustrated by the example in the docs linked above:
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
To get the result, you should place the
$last_row = mysqli_insert_id($connection);
after your INSERT query
For other people coming here, maybe you tried INSERT IGNORE INTO
and you have a UNIQUE
value that was already inserted. In that case, this id is zero.
Also you'll get "zero" if MySQL runs out of connections. I'm no expert on persistent connections but this might help somebody?
As you probably know PHP “mysql” extension supported persistent connections but they were disabled in new “mysqli” extension --Peter Zaitsev