codeigniter插入多行(带扭曲)

时间:2016-02-15 13:39:09

标签: php codeigniter

在我的控制器中我有这些变量

$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

这里会发生的是,数组中的IDs会收到相同的messageContentmessageSubject。我将如何在CodeIgniter中实现它? insert_batch()需要一个包含所有值的数组,但在我的情况下,只有IDs在数组中。

我目前的工作是:

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

1 个答案:

答案 0 :(得分:1)

您仍然可以使用insert_batch。你只需要为它构建一个合适的数组:

$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);
}

然后在你的模型中:

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