2013-12-18 18 views
0

下面是我的代碼:我已經插入一張表,並與insert_id我想獲得該行,但它沒有發生?

//In one of my model(name is commonmodel) I wrote 
    public function create_and_get($table,$data){ 
    $this->db->insert($table,$data); //It's okay 
    $lastid= $this->db->insert_id(); 
    $getback=$this->db->get($table,array('id'=>$lastid))->result_array(); 
    return $getback[0]; 

在控制器---基本上這是一個Ajax調用等等..

$stored=$this->commonmodel->create_and_get('party',$data); 
    echo json_encode($stored); exit; 

當Ajax響應我打電話..

var obj=$.parseJSON(res) //I get the object at console.log(obj) 
    //but it's the first row every time from the 'party' table.. 

我'這麼詛咒與這個錯誤和一些其他ID黑客...請幫助..

+1

您確定A)插入是否發生,並且您是否檢查了$ lastid = $ this-db-> insert_id()行的狀態?可以var_dump($ lastid) - 我的猜測是它的0 – Rottingham

+0

是的,我的控制檯顯示我..和Nah .. last_id是正確的,但我不知道爲什麼它每次返回第一行..我交叉檢查,但沒有運氣.. – edam

+0

那麼這將是你的db-> get()控制器的問題。或者,如果表上的ID字段不是唯一的自動遞增字段,則可能有多個具有相同ID值的行,並且 - > get()調用將獲得第一個找到的行。 – Rottingham

回答

0

我知道你有解決它,但我認爲這是一個更好的解決方案,只是返回您用於插入的數據,而不是再次查詢數據庫。

像這樣的工作:

public function create_and_get($table,$data) { 

    $this->db->insert($table,$data); 
    $lastid = $this->db->insert_id(); 
    $data['id_field_name'] = $lastid; 
    return $data; 

} 

這將節省您的另一行做DB。

相關問題