Search code examples
phparrayscodeignitertransposebatch-insert

Transpose sets of repeatable fields and insert all records using CodeIgniter


I'm trying to loop through an array and insert my values into the database. My table looks like this:

  • hours_day
  • hours_open
  • hours_close

My form enables the user to select a day, an opening time and a closing time. There is a plus button which adds another day below it, so the user can choose whichever days they wish. This means that my select box names are arrays, i.e. hours_day[]

My Model looks like this:

$hours = array(
    'hours_day' => $this->input->post('venue_hours_day'),
    'hours_opening' => $this->input->post('venue_hours_open'),
    'hours_closing' => $this->input->post('venue_hours_close'),
);

So I have an array ($hours) with arrays inside of it (hours_day, hours_opening, hours_closing). How do I loop through this an add it to my database?


Solution

  • You can use :

    $post_day = $this->input->post('venue_hours_day');
    $post_opening = $this->input->post('venue_hours_open');
    $post_closing = $this->input->post('venue_hours_closing');
    
    $count = count($post_day);
    $results = array();
    
    for ($i = 0; $i < $count; $i++)
    {
        $results []= array(
          'hours_day' => $post_day[$i],
          'hours_opening' => $post_opening[$i],
          'hours_closing' => $post_closing[$i]
        );
    }
    
    $this->db->insert_batch('your_table', $results);