简体   繁体   English

获取单个mysqli查询中插入的所有行的insert_id(多个值)

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

Working in PHP and using MYSQLI. 使用PHP并使用MYSQLI。 Trying to get the insert_id for all rows inserted from a single insert query with multiple values. 尝试获取从具有多个值的单个插入查询插入的所有行的insert_id。 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: 但是,这是一些仅包含4个值的插入的示例代码:

$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. 上面的代码实现了插入,但是只给了我调用中第一次插入的ID。 How can I retrieve all of the ID's for this single query? 如何为该单个查询检索所有ID?

可以安全地假设您的ID是mysql_insert_id +连续的下3个(无论是哪个),因为您的语句是在一个事务中完成的

No, this isn't possible with MySQL. 不,这在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. 它甚至没有真正节省使用LAST_INSERT_ID() ,因为它将返回一个BIGINT(64位)值,该值表示成功为AUTO_INCREMENT列成功插入的第一个自动生成的值。

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. 您可能会猜到该值+数据列表的长度将是ID的值,但没有绝对的保证,这将永远是正确的。

As @thomas pointed , I used this solution and suppose it's ok to detect last insert id; 正如@thomas所指出的 ,我使用了这种解决方案,并认为可以检测到最后一个插入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);

$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. 同时,我使用multi_query并在while循环中处理了结果,但无法达到预期的结果。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM