如何在codeigniter中获取多个插入的id

时间:2021-06-13 20:15:36

I am writing a Codeigniter script where I have inserted multiple rows using foreach . I want to get all the last inserted id's.

我正在编写一个Codeigniter脚本,我使用foreach插入了多行。我想得到所有最后插入的id。

Here is my code:

这是我的代码:

public function savePickupDataModal($dates, $pickData) {
    foreach ($dates['dates'] as $date) {
        $sql = 'INSERT INTO pickupManagement (dates, readyhour, readymint, readyformat, latesthour, latestmint, latestformat, approxVal, otherComment) ' .
                    'VALUES("' . $date . '","' . $pickData['readyhour'] . '","' . $pickData['readymint'] . '","' . $pickData['readyformat'] . '","' . $pickData['latesthour'] . '","' . $pickData['latestmint'] . '","' . $pickData['latestformat'] . '","' . $pickData['approxVal'] . '","' . $pickData['otherComment'] . '")';
        $query = $this->db->query($sql);
        if ($this->db->affected_rows() > 0) {
            return true;
        } else {
            return false;
        }
    }
}

Here the date array contains any number of dates like 3, 4 or 5 so the insert query will be executed until the array contains the number of dates.

这里的日期数组包含任意数量的日期,如3,4或5,因此插入查询将被执行,直到数组包含日期数。

How do I get all the last inserted records id's?

如何获取所有最后插入的记录ID?

1 个解决方案

#1


1  

In your case you are actually performing multiple independent queries, so you can get the last id and push it into an array over and over.

在您的情况下,您实际上正在执行多个独立查询,因此您可以获取最后一个ID并将其一遍又一遍地推送到数组中。

$affected_ids = array();
foreach(....

    $query = .....
    if($this->db->affected_rows() > 0)
        $affected_ids[] = $this->db->insert_id();

}
echo '<pre>', print_r($affected_ids),'</pre>';

There doesn't seem to be any need to actually return true or false here.

似乎没有必要在这里实际返回true或false。

#1


1  

In your case you are actually performing multiple independent queries, so you can get the last id and push it into an array over and over.

在您的情况下,您实际上正在执行多个独立查询,因此您可以获取最后一个ID并将其一遍又一遍地推送到数组中。

$affected_ids = array();
foreach(....

    $query = .....
    if($this->db->affected_rows() > 0)
        $affected_ids[] = $this->db->insert_id();

}
echo '<pre>', print_r($affected_ids),'</pre>';

There doesn't seem to be any need to actually return true or false here.

似乎没有必要在这里实际返回true或false。