简体   繁体   中英

How to get the id of multiple insert in codeigniter

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

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.

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

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.

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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