PHP MySQLi insert ids from multi_query()

后端 未结 1 2003
你的背包
你的背包 2021-01-22 12:48

Is there a way to get the last generated auto_increment IDs after inserting several rows with mysqli multi_query function?

EDIT:

I managed to get it work by addi

1条回答
  •  囚心锁ツ
    2021-01-22 13:39

    You can fetch the different insert ids by calling MySQLi's next_result() for each consecutive insert statement. As far as I know, you don't have to store any results as long as the queries are insert statements or something else that doesn't return a result set.

    $sql = new MySQLi("...");
    $query = "INSERT STATEMENT NUMBER ONE;";
    $query .= "INSERT STATEMENT NUMBER TWO;";
    $query .= "INSERT STATEMENT NUMBER THREE";
    $sql->multi_query($query);
    
    // The first insert id will be available at once
    $id1 = $sql->insert_id;
    
    // The second needs to be handeled a little differently
    $sql->next_result();
    $id2 = $sql->insert_id;
    
    // And lastly the third one
    $sql->next_result();
    $id3 = $sql->insert_id;
    

    You can also put this in a loop if you are unsure of how many insert statements there are:

    $ids = array();
    do
    {
        $ids[] = $sql->insert_id;
        $sql->next_result();
    } while($sql->more_results());
    

    This is untested pseudo code (as you might have figured), but it should work.

    0 讨论(0)
提交回复
热议问题