2012-03-29 32 views
0

私はこのメッセージを書いてユーザーに新しい個人的なメッセージを送信しましたが、私はこれをやり直す方法を見つけようとしています。ループの中でクエリを実行するのは、何百ものクエリに蓄積され、代わりに一度に1つのクエリを実行する可能性があるからです。私は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; 
} 

EDIT:既に$ recipientsという配列があるため、追加のアイデアはありません。

+0

の下に、これを参照してください、一度にクエリを挿入しますバッチ挿入.Thisで試してみてください$ recipients配列には –

答えて

2

あなたはこれをしたくありません。何あなたを投稿してください相互作用は一回

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') 

を行わデシベルので、リンク http://codeigniter.com/user_guide/database/active_record.html#insert

+0

が含まれていますが、配列の最初の部分だけが必要ですが、私のコードではどうですか? –

+0

はい、あなたはdocのような配列を作成して、次に進むことができます –

+0

私のforeachではどうしたらうまくいくのですか? –

関連する問題