I have two tables in MySql database, one is sales_order and the other is sales_order_details which contains the details of the order in the sales_order table. Obviously, there is a one to many relationship from sales_order to sales_order_details.
When a customer places an order, the first entry is made into the sales_order table and based on the auto_increment id of the sales_order table, the corresponding entry is made into the sales_order_details table.
I’m using the last_insert_id() MySql function to retrieve the corresponding order_id from the sales_order table, Something like this.
insert into sales_order_details(order_id, prod_id, prod_price)values(last_insert_id(), 5, 1500);
It’s working. The last_insert_id() function retrieves the last inserted id from the respective table which is unique to a particular connection (as far as I know).
Now, I need the same order_id which is retrieved and inserted most recently by the last_insert_id() function to send it as an invoice number to a payment system.
I can try using the PHP function mysql_insert_id() but I’m not sure whether it works as specified. What is the correct way to retrieve the last insert id which always guarantees to retrieve the specific id which is always associated with a particular order?
There are 2 ways which you could solve this:
After inserting the entry in the sales_order:
Get the
last_insert_idand store it in a php variable, then inject this value into the relevant queries.Store the
last_insert_idin a MySql user-defined variable and use the variable in the query instead oflast_insert_id.sample code for option 2
SET @last_order_id = last_insert_id();