2010-11-12 123 views
4

請參考這個問題,我問
Codeigniter Insert Multiple Rows in SQL笨插入多維數組排在MySQL

要重申

<tr> 
<td><input type="text" name="user[0][name]" value=""></td> 
<td><input type="text" name="user[0][address]" value=""><br></td> 
<td><input type="text" name="user[0][age]" value=""></td> 
<td><input type="text" name="user[0][email]" value=""></td> 
</tr> 
<tr> 
<td><input type="text" name="user[1][name]" value=""></td> 
<td><input type="text" name="user[1][address]" value=""><br></td> 
<td><input type="text" name="user[1][age]" value=""></td> 
<td><input type="text" name="user[1][email]" value=""></td> 
</tr> 
.......... 

可以插入MySQL作爲本

foreach($_POST['user'] as $user) 
{ 
    $this->db->insert('mytable', $user); 
} 

此結果在多個MySQL查詢中。是否有可能進一步優化它,使得插在一個查詢時

像這樣的事情

insert multiple rows via a php array into mysql

但考慮codeigniters的優勢,簡單的語法。謝謝

+4

除非你有記錄的幾十萬插入,你不會得到任何東西,真正的瓶頸是表的索引,而不是圓多次運行查詢的成本。 – 2010-11-12 15:34:41

回答

0

CodeIgniter似乎沒有多插入方法。此外,即使有,你可能會遇到這樣的問題:

  • 擊中最大查詢長度上限
  • 有鎖定該表直至插入完成
  • 處理錯誤可能會有點困難
  • ...
0

Codeigniter 2(即將發佈)將有一個批量插入方法。

+0

謝謝,我已經在使用ci 2,會查閱文檔。 – 2010-11-13 11:08:33

0

在CI 2中,有一個set_insert_batch() Active Record功能。

+1

儘管沒有文檔,並且我組裝的數組沒有插入 – 2011-01-03 01:59:42

3

它現在證明以及可能對別人有用:

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