Dev
Dev

Reputation: 1746

codeigniter insert multiple rows (with a twist)

In my controller I have these variables

$recipients = $this->input->post('messageRecipients'); // array of recipients
// Looks like this
// Array ( 
//     [0] => 12102719 
//     [1] => 12103895 
// ) 
$subject = $this->input->post('messageSubject'); // just a string
$content = $this->input->post('messageContent'); // just a string

What will happen here is that the IDs in the array will received the same messageContent and messageSubject. How will I implement this in CodeIgniter? The insert_batch() needs an array that contains all the values but in my case, only the IDs are in array.

My current work around right now is:

$numRecipients = sizeof($recipients);
for($ctr=0; $ctr<$numRecipients; $ctr++){   
   // loop each recipient ID and call model         
   $this->Message_model->sendMessage($recipients[$ctr],$subject,$content);
}

Upvotes: 1

Views: 61

Answers (1)

AdrienXL
AdrienXL

Reputation: 3008

You still can use insert_batch. You just need to build a proper array for that :

$subject = $this->input->post('messageSubject');
$content = $this->input->post('messageContent');
$insert_array = array();

foreach($recipients as $r)
{
     $insert_array[] = array('db_field1' => $r, 
                             'db_field2' => $subject, 
                             'db_field3' => $content);
}

And then in your model :

$this->db->insert_batch('mytable', $insert_array);

Upvotes: 1

Related Questions