I know how LAST_INSERT_ID() works for auto incremented columns, but I cannot find a way to get the last id I inserted for a non auto incremented column.
Is there a way I can do that?
If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL.
Obtaining the value of column that uses AUTO_INCREMENT after an INSERT statement can be achieved in a number of different ways. To obtain the value immediately after an INSERT , use a SELECT query with the LAST_INSERT_ID() function.
You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).
How to get last inserted id of a MySQL table using LAST_INSERT_ID() We will be using the LAST_INSERT_ID() function to get the last inserted id. Last_insert_id() MySQL function returns the BIG UNSIGNED value for an insert statement on an auto_increment column.
you can easily do that using the same LAST_INSERT_ID()
.
INSERT INTO thetable (id, value)
VALUES (LAST_INSERT_ID(126), 'some data');
SELECT LAST_INSERT_ID(); -- returns 126
I'm assuming you want the retrieve this last inserted id at some later point after inserting it, since if you need it right after inserting it you obviously would already know what the id is.
The only way you'll be able to get that is to have another column on the table that can indicate which row was last inserted, such as a timestamp or datetime column. If your ids are unique and increasing, you can just use that column. Then you just select 1 row ordered by that column in descending order.
For example
INSERT INTO my_table (id, timestamp) VALUES (123, NOW())
SELECT id FROM my_table ORDER BY timestamp DESC LIMIT 1
Edit: as per the comments below, you're much better off using an AUTO_INCREMENT column, though this column doesn't have to be the id
column, you could add an auto-increment insert_order
column of type Int
and simply order by that.
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