Retrieving the last insert id from MySql using PHP

前端 未结 7 1084
时光说笑
时光说笑 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条回答
  •  -上瘾入骨i
    2020-12-22 09:17

    mysql_insert_id( ) always returns the id generated for an AUTO_INCREMENT collumn by the previous query. (See the PHP Manual)

    I don't understand exactly which id you want to fetch, but in order to retrieve it using PHP you should always do so directly after the query. For example:

    // Query A
    
    mysql_query( 'INSERT INTO table_a ( id, name ) VALUES ( NULL, "Henry" )' );
    $idA = mysql_insert_id( );
    
    // Query B
    
    mysql_query( 'INSERT INTO table_b ( id, name, a_id ) VALUES ( NULL, "Wotton", ' . $idA . ' )' );
    $idB = mysql_insert_id( );
    
    // Query C
    mysql_query( 'INSERT INTO table_c ( id, name, a_id ) VALUES ( NULL, "Rick", ' . $idA . ' )' );
    

    The advantage of storing them in a PHP variable is that your system or framework can't mess up your queries by performing another query while you are not aware of it.

提交回复
热议问题