簡體   English   中英

如何在codeigniter中獲取所有插入的記錄ID?

[英]How to get all inserted records ids in codeigniter?

如何在codeigniter中獲取所有插入的記錄ID? 我在使用insert_batch函數插入多個記錄,但是codeigniter $ this-> db-> insert_id()函數僅返回最后一個記錄ID。 //但是我需要所有插入的記錄ID。 如果有人有想法請幫助。

//In codeigniter this function returns only last inserted record id.

function insertStudent(){

    $data[] = array('firstname'=>'firstname1','lastname'=>'lastname1');

    $data[] = array('firstname'=>'firstname2','lastname'=>'lastname2');

    $result = $this->db->insert_batch( 'student', $data );

    return $this->db->insert_id();

}

這可以通過使用第一個id和count來實現。

  1. 獲取要插入的數據計數。 (例如,您的示例中為2)
  2. 通過$this->db->insert_id()獲取第一個插入ID(例如說30)
  3. 現在獲取最后插入的記錄ID等於= first record id - (count - 1) (例如30 +(2-1)= 31)

現在,您可以查詢以獲取ID在30到31之間的數據。

如果絕對必須為每個插入的行都具有insert_id,則最簡單的最可靠的方法是循環多個插入,而不是制作一個大的胖插入。

循環遍歷多個插入將允許您獲取所有insert_id。 如果其中一行插入失敗,並且數據庫因此拒絕所有數據,它也將允許您不丟失所有數據。

這是一種有效的方法:

由於您的記錄具有結果ID,因此我將假設它們也自動遞增。

如果是這種情況,請執行此操作,並且仍然使用insert_batch。

這是您的工作:

  1. 您對要插入的項目進行計數:

    $ count = count($ data);

  2. 運行您的批處理插入:

    $ this-> db-> insert_batch('student',$ data);

  3. 獲取您的批次的第一個插入的ID:

    $ first_id = $ this-> db-> insert_id();

  4. 將計數(減1)添加到插入ID中以獲取最后的記錄ID。

    $ last_id = $ first_id +($ count-1);

你去! 現在,您有了插入記錄的第一個和最后一個ID,並且通過擴展,還可以找到其間的所有其他內容。

function insertStudent(){

    $data[] = array('firstname'=>'firstname1','lastname'=>'lastname1');

    $data[] = array('firstname'=>'firstname2','lastname'=>'lastname2');

    $result = $this->db->insert_batch( 'student', $data );

    $a= $this->db->get('student');
    $data = $a->result_array();
    echo($data[0]['id']);

}

希望對您有幫助。

我最好的解決方案是更新DB_driver.php。

public function is_write_type($sql)
{
  return (bool) (preg_match('/^\s*"?(SET|INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE|LOAD|COPY|ALTER|RENAME|GRANT|REVOKE|LOCK|UNLOCK|REINDEX)\s+/i', $sql);
}
  • 至:
public function is_write_type($sql)
{
  return (bool) (preg_match('/^\s*"?(SET|INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE|LOAD|COPY|ALTER|RENAME|GRANT|REVOKE|LOCK|UNLOCK|REINDEX)\s+/i', $sql) && !preg_match('/ RETURNING /i', $sql));
}

最安全的方法是:

  1. 在表中添加列code
  2. 批量插入[id session user]-[current time stamp]前,請創建代碼。
  3. 將具有該代碼的所有元素批量插入code
  4. 查詢一個Select搜索該代碼,您將在批量插入時插入所有元素

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM