使用CodeIgniter中的批处理插入获取查询的最后插入ID时出错

Jer*_*lle 3 php mysql codeigniter

如何使用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
Run Code Online (Sandbox Code Playgroud)

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

Soh*_*ail 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);
Run Code Online (Sandbox Code Playgroud)