Get all inserted IDs when inserting multiple rows using a single query

前端 未结 7 1028
误落风尘
误落风尘 2021-01-17 11:40

I\'ve already looked at other answers and I still feel that my question is relevant and deserves a separate entry.

I have a table named settings(which stores user se

相关标签:
7条回答
  • 2021-01-17 12:12

    How about:

    $id = array();
    
    $sql = "INSERT INTO `table` VALUES ('', 'foo', 'bar');";
    $sql .= "INSERT INTO `table` VALUES ('', 'foo', 'bar');";
    $sql .= "INSERT INTO `table` VALUES ('', 'foo', 'bar');";
    $sql .= "INSERT INTO `table` VALUES ('', 'foo', 'bar');";
    $sql .= "INSERT INTO `table` VALUES ('', 'foo', 'bar');";
    $sql .= "INSERT INTO `table` VALUES ('', 'foo', 'bar');";
    
    if ($db=new mysqli('host', 'user', 'pass', 'dbase'))
    {
        $db->multi_query($sql);
    
        if ( isset($db->insert_id) ) $id[] = $db->insert_id;
    
        while ($db->more_results())
        {
            if ($db->next_result()) $id[] = $db->insert_id;
            else trigger_error($db->error);
        }
    
        $db->close();
    }
    else trigger_error($db->error);
    
    if (count($id) == 0) trigger_error('Uh oh! No inserts succeeded!');
    else print_r($id);
    

    Perhaps this would return your insert ids like you are wanting. I haven't tested it, but perhaps you could adapt it for your purpose and who knows it might actually work.

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