Search code examples
phpcodeignitercodeigniter-3codeigniter-query-builder

How to use two foreach to insert data in database


I have two arrays from my view.I need to insert their data corresponding to each other.

Below is the My view

<?php foreach ($seats as $seat):?>

        <tr>
            <td><input type="checkbox" name="seat_id[]" value=<?php echo $seat->seatNumber;?>></td>
            <td><?php echo $seat->seatLabel;?></td>
            <td><input type="hidden" name="seat_label[]" value="<?php echo $seat->seatLabel;?>"></td>
        </tr>
        <?php endforeach;?>

From above view seat_id and seat_label carries values that have to be stored in database

This is my controller

if($this->form_validation->run()){
            $seat_ids = $this->input->post("seat_id[]");
            $seat_labels = $this->input->post("seat_label[]");
            $busNumber = $this->input->post("busNumber");
            $bookingDate = $this->input->post("bookingDate");
            $reportingTime = $this->input->post("reportingTime");
            $departureTime = $this->input->post("departureTime");
            $this->load->model('Queries');
     $insert = $this->Queries->saveMessage($seat_ids, $seat_labels, $busNumber, $bookingDate, $reportingTime, $departureTime);

This is My model

public function saveMessage($seat_ids, $seat_labels, $busNumber, $bookingDate, $reportingTime, $departureTime){

    foreach($seat_ids as $seat_id )
          foreach($seat_labels as $seat_label ){
    {
        $record = array(
        'seatNumber' => $seat_id, 
        'seatLabel'  => $seat_label,
        'bookingDate' => $bookingDate,
        'reportingTime' => $reportingTime,
        'departureTime' => $departureTime, 
        'busNumber' => $busNumber,
        'seatUse' => 'Enabled',
        'seatStatus' => 'Available',);
        $this->db->insert('schedule', $record);
    }

Solution

  • Hope this will help you :

    Use insert_batch instead of insert like this :

    public function saveMessage($seat_ids, $seat_labels, $busNumber, $bookingDate, $reportingTime, $departureTime)
    {
    
        foreach($seat_ids as $key => $seat_id )
        {
                $record[] = array(
                'seatNumber' => $seat_id, 
                'seatLabel'  => $seat_labels[$key],
                'bookingDate' => $bookingDate,
                'reportingTime' => $reportingTime,
                'departureTime' => $departureTime, 
                'busNumber' => $busNumber,
                'seatUse' => 'Enabled',
                'seatStatus' => 'Available');
        }
        $this->db->insert_batch('schedule', $record);
    }
    

    For more :https://www.codeigniter.com/user_guide/database/query_builder.html#inserting-data