使用CodeIgniter进行批量插入查询时,获取最后插入的ID出现错误

3

如何在CodeIgniter中使用批量插入查询获取最后一次插入的ID。我使用了代码$this->db->insert_id(),但它返回我第一个插入数组的ID,我无法获取最后一次插入。

以下是我的操作:

for ($x = 0; $x < sizeof($filtername); $x++) {
    $orders[] = array(
        'poid'              => null,
        'order_id'          => $poid,
        'item_desc'         => $filtername[$x],
        'item_qty'          => $filterquantity[$x],
        'item_price'        => $filterprice[$x],
        'total'             => $filtertotal[$x],
        'cash_on_delivery'  => $val_delivery,
        'is_check'          => $val_check,
        'bank_transfer'     => $val_transfer,
        'transaction_date'  => $dateorder
    );
}

$this->db->insert_batch('po_order', $orders);
echo $this->db->insert_id(); //will return the first insert array

我找不到我的错误在哪里。我最后的选择是使用查询来获取它。我也使用了 mysql_insert_id() 但总是返回0。


https://dev59.com/LknSa4cB1Zd3GeqPNmdP - Mahavir Munot
2
https://dev59.com/QnDYa4cB1Zd3GeqPD8AT - Mahavir Munot
将您插入的记录数量添加到第一个返回的ID中可以帮助您,除非您没有在数据库中删除先前的记录。因为insert_batch不会给出最后插入的ID。 - plain jane
希望这可以帮到你...... https://dev59.com/Y3M_5IYBdhLWcg3wp0-l - plain jane
2个回答

5

我认为在处理性能时,最好使用批量插入而不是在循环中进行单个插入操作。但若要获取最后一次插入的ID,则需要将第一次插入的ID与受影响的行数相加。

$this->db->insert_batch('po_order', $orders);
$total_affected_rows = $this->db->affected_rows();
$first_insert_id = $this->db->insert_id();

$last_id = ($first_insert_id + $total_affected_rows - 1);

1
这种技术非常简单且更快。 - Kabir Hossain
2019年仍然有用。谢谢兄弟! - MONSTEEEER

3

您需要像这样做:

$insertIds  = array();
for ($x = 0; $x < sizeof($filtername); $x++) {
    $orders = array(
        'poid'              => null,
        'order_id'          => $poid,
        'item_desc'         => $filtername[$x],
        'item_qty'          => $filterquantity[$x],
        'item_price'        => $filterprice[$x],
        'total'             => $filtertotal[$x],
        'cash_on_delivery'  => $val_delivery,
        'is_check'          => $val_check,
        'bank_transfer'     => $val_transfer,
        'transaction_date'  => $dateorder
    );
    $this->db->insert('po_order', $orders);
    $insertIds[$x]  = $this->db->insert_id(); //will return the first insert array
}
print_r($insertIds); //print all insert ids

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接