Get insert_id for all rows inserted in single mysqli query (multiple values)

自闭症网瘾萝莉.ら 提交于 2019-11-27 06:28:21

问题


Working in PHP and using MYSQLI. Trying to get the insert_id for all rows inserted from a single insert query with multiple values. Keeping it in a single call for efficiency. My actual code has hundreds of values in one insert query. However, here is some sample code for an insert with just 4 values:

$sql = "INSERT INTO link_tags ( string_names_id, urls_id ) 
    VALUES ( '2', '17' ), ( '8', '31' ), ( '8', '1' ), ( '8', '4' )";

$mysqli->query($sql);

echo "id's: " .$mysqli->insert_id;

The above code achieves the insert, but only gives me the id of the first insert from the call. How can I retrieve all of the ID's for this single query?


回答1:


It should be safe to assume that your ids are mysql_insert_id + the next 3 (whatever) in succession, as your statement is done in one transaction




回答2:


No, this isn't possible with MySQL.

Its not even really save to use LAST_INSERT_ID() as it will return a BIGINT (64-bit) value representing the first automatically generated value successfully inserted for an AUTO_INCREMENT column.

You could guess that this value + length of your data list will be the ID's but there isn't any absolute guarantee this will always be true.




回答3:


As @thomas pointed, I used this solution and suppose it's ok to detect last insert id;

$id = $link->insert_id;
if ($id && $link->affected_rows > 1) {
    $id = ($id + $link->affected_rows) - 1; // sub first id num
}

In your situation (for all ids);

$id = $link->insert_id; $ids = [$id];
if ($id && $link->affected_rows > 1) {
    for ($i = 0; $i < $link->affected_rows - 1; $i++) {
        $ids[] = $id + 1;
    }
}

// or more dirty way
$id = $link->insert_id; $ids = [$id];
if ($id && $link->affected_rows > 1) {
    $ids = range($id, ($id + $link->affected_rows) - 1);
}

Meanwhile, I used multi_query and handled result in while loop but could not achieve expected result.

while ($link->more_results() && $link->next_result()) $ids[] = $link->insert_id;


来源:https://stackoverflow.com/questions/15663918/get-insert-id-for-all-rows-inserted-in-single-mysqli-query-multiple-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!