Php 批量插入查询到一个
我写这条消息是为了向用户发送一条新的个人消息,但是我正在尝试找出如何重新执行这一点,因为我被告知我不应该在循环中执行查询,因为这可能会累积到数百个查询,而一次只执行一个查询。我正在使用CodeIgniter的数据库类,更具体地说是它的活动记录类Php 批量插入查询到一个,php,codeigniter,Php,Codeigniter,我写这条消息是为了向用户发送一条新的个人消息,但是我正在尝试找出如何重新执行这一点,因为我被告知我不应该在循环中执行查询,因为这可能会累积到数百个查询,而一次只执行一个查询。我正在使用CodeIgniter的数据库类,更具体地说是它的活动记录类 function sendMessage($recipients, $subject, $message, $sender, $bcc = array()) { // Check args if(!is_array($recipients
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;
}
编辑:任何其他想法,因为我已经有一个名为$recipients的数组。您不想这样做。请尝试批量插入。这将一次插入查询,因此db交互只执行一次 从codeigniter文档开始
$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')
请参考以下链接
虽然我只需要数组的第一部分,但我的代码是这样的,不是吗?是的,您可以像在文档中一样创建数组,然后继续,您不需要使用批插入循环。您只需使用循环创建和数组,然后只需传递这个数组$this->db->insert_batch('mytable',$data);请发布$recipients数组包含的内容