批量插入查询到一个

时间:2012-03-29 03:38:50

标签: php codeigniter

我写过这条消息是为了向用户发送一条新的个人信息,但是我想知道如何重做这一点,因为我被告知我不应该在里面做一个查询一个循环,因为它可以累积到数百个查询,而是一次执行一个查询。我正在使用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;
}

编辑:任何其他想法,因为我已经有一个名为$ recipients的数组。

1 个答案:

答案 0 :(得分:2)

你不想这样做。请尝试批量插入。这将立即插入查询,因此数据库交互只进行了一次

至于codeigniter docs

$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