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。

4

2 回答 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);
于 2013-12-17T08:09:08.320 回答
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
于 2013-08-22T07:11:30.550 回答