Retrieving the last insert id from MySql using PHP

前端 未结 7 1087
时光说笑
时光说笑 2020-12-22 08:38

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 s

7条回答
  •  执念已碎
    2020-12-22 09:25

    Both *LAST_INSERT_ID()* and *mysql_insert_id()* work as advertised i.e.: they will retrieve the last id inserted into any table during the current session/connection.

    As long as you do not insert into more than one auto incremented table before retrieving this id, you're sure it's the correct one.

    Also be careful when inserting multiple values into the same table, you'll receive the value for the first one of them but they are not necessarily consecutive (a different session/connection could have inserted some new records too).

    I usually like to do things like this:

    START TRANSACTION;
        INSERT INTO sales_order ...;
        SET @last_order = LAST_INSERT_ID();
        INSERT INTO sales_order_details (order_id) VALUES ($last_order);
        SELECT @last_order;
    COMMIT;
    

    The result-set of this query should contain a single column and a single row holding the value of the last order.

    But then again I usually do that for transactional safety of updates most of all.

    START TRANSACTION;
        SELECT * FROM sales_order WHERE order_id = 2 FOR UPDATE;
        UPDATE sales_order_details SET quantity = 9 WHERE order_id = 2 AND prod_id = 3;
        UPDATE sales_order SET price_to_pay = (SELECT SUM(quantity*price) FROM sales_order_details WHERE order_id = 2);
    COMMIT;
    

    The transaction should ensure the operations are atomic (all done without interruption by other processes);

    If you were to do the same without a transaction or from the application code, the quantity might be updated by another thread and read by a third thread before you were done updating the price. Yielding a false "price_to_pay" to the user.

提交回复
热议问题