简体   繁体   English

在CodeIgniter中使用批量插入获取查询的最后一个插入ID时出错

[英]Error in getting the last inserted ID of a query using batch insert in CodeIgniter

How can I get the last inserted ID of a query using the batch insert in CodeIgniter. 如何使用CodeIgniter中的批量插入获取最后插入的查询ID。 I used the code $this->db->insert_id() but it returns the ID of my first inserted array. 我使用代码$this->db->insert_id()但它返回我第一个插入数组的ID。 I can't get the last insert. 我无法获得最后一次插入。

Here's what I did: 这是我做的:

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

I can't spot where's my error. 我无法发现我的错误在哪里。 My last option is to get it using a query. 我的最后一个选择是使用查询来获取它。 I also did mysql_insert_id() but always returns to 0. 我也做了mysql_insert_id()但总是返回0。

I think the best way would be to use the batch insert instead of individual inserts in a loop for performance , but to get the last insert id, ADD the First Insert ID & the Affected Rows. 我认为最好的方法是在循环中使用批量插入而不是单个插入来提高性能,但要获取最后一个插入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);

You will need to do something like this, 你需要做这样的事情,

$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

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

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