我写这条消息是为了向用户发送一条新的个人消息,但我正在努力找出如何重做这条消息,因为有人告诉我不应该在循环中进行查询,因为这可能会累积到数百个查询,而会一次进行一个查询。我正在使用CodeIgniter的数据库类,更具体地说是它的Active Record类
function sendMessage($recipients, $subject, $message, $sender, $bcc = array())
{
// Check args
if(!is_array($recipients)) { throw new Exception('Non-array $recipients provided to sendMessage()'); }
if(!is_string($subject)) { throw new Exception('Non-string $subject provided to sendMessage()'); }
if(!is_string($message)) { throw new Exception('Non-string $message provided to sendMessage()'); }
if(!is_numeric($sender)) { throw new Exception('Non-numeric $userID provided to sendMessage()'); }
if(!is_array($bcc)) { throw new Exception('Non-array $bcc provided to sendMessage()'); }
$this->db->set('subject', $subject);
$this->db->set('senderID', $sender);
$this->db->set('message', $message);
$this->db->insert('usersPersonalMessages');
if ($this->db->affected_rows() == 1)
{
$insertID = $this->db->insert_id();
foreach ($recipients as $recipientID)
{
$this->db->set('userID', $recipientID);
$this->db->set('usersPersonalMessagesID', $insertID);
$this->db->insert('usersPersonalMessagesRecipients');
if ($this->db->affected_rows() == count($recipients))
{
continue;
}
}
if (isset($bcc) && (!empty($bcc)))
{
foreach ($bcc AS $bccID)
{
$this->db->set('userID', $bccID);
$this->db->set('usersPersonalMessagesID', $insertID);
$this->db->set('type', 2);
$this->db->insert('usersPersonalMessagesRecipients');
}
if ($this->db->affected_rows() == count($bcc))
{
continue;
}
}
continue;
}
return TRUE;
}
编辑:任何其他想法,因为我已经有了一个名为$receives的数组。
您不想这样做。请尝试批量插入。这将一次插入查询,因此数据库交互只完成一次
截至代码点火器文档
$data = array(
array(
'title' => 'My title' ,
'name' => 'My Name' ,
'date' => 'My date'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name' ,
'date' => 'Another date'
)
);
$this->db->insert_batch('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')
请参阅下面的链接http://codeigniter.com/user_guide/database/active_record.html#insert