2012-03-15 17 views
0

在Codeigniter中,如果我創建了一個執行多次插入的SQL字符串,那麼如何獲取每個插入的ID?如何獲取codeigniter中批量插入的ID?

// Prepare the SQL 
$sql = ''; 
$chunk = array(array(), array(), array()); // The elements are arrays 
foreach($chunk as $arr){ 
    // The first field is the primary key (INT NOT NULL auto_increment) 
    $sql .= "(NULL, {$arr[0]}, {$arr[1]}, {$arr[2]}, {$arr[3]}, {$arr[4]})"; 
    if($arr!= $last) $sql .= ', '; 
} 

// Start inserting into the db 
$this->db->trans_start(); 
$this->db->query('INSERT INTO my_table VALUES '.$sql); 
// A few other queries go here which need the IDs of the previous insert 
$this->db->trans_complete(); 

這也是我第一次使用交易。

回答

0

我決定改用交易。

+0

你能分享你如何管理去分享插入值的ID嗎? – Searock 2015-07-31 09:56:29

0

您可能需要在插入前記錄MAX標識,然後選擇大於批量插入後的所有ID。

編輯:

我發現這個在MySQL manual

使用LOCK TABLES和UNLOCK對事務表,例如InnoDB表TABLES的正確方法,是開始交易與SET autocommit = 0(不是START TRANSACTION),後面是LOCK TABLES,在顯式提交事務之前不要調用UNLOCK TABLES。

+0

是否有可能一旦我獲得MAX ID,其他用戶突然做一個類似的插入,然後我可以做我自己的,從而遞增MAX ID?這有可能發生嗎? – enchance 2012-03-15 20:39:25

+0

這就是表鎖是 – landons 2012-03-15 22:29:01

+0

對不起,我是mysql新手,但是當我使用事務時會自動發生嗎? – enchance 2012-03-16 05:21:50