2011-08-04 31 views
5

我只是試圖從codeiginitor的mysql表中獲取最新的自動生成密鑰。但它不是如何工作。我曾嘗試這個代碼
$this->db->insert_id()
以及
$this->db->mysql_insert_id()
我收到以下錯誤
Severity: Notice
Message: Undefined property: CI_DB_mysql_driver::$insert_id

不支持MySQL的INSERT_ID功能?我們如何使它工作?

+0

是否正常[mysql_insert_id()](http://ro.php.net/manual/de/function.mysql-insert-id。PHP)爲你工作? – sqwk

+1

這將有助於查看您在哪裏運行查詢。 –

+0

@sqwk我只能在安裝MySQLi後才能在普通PHP上獲得Insert id。我認爲mysql_insert_id只能用於MySQLi。我不知道如何讓CodeIgnitor使用MySQLi –

回答

5

這是我試圖插入數據並獲取插入的ID代碼,

$this->db->insert('table_name',$data); $id = $this->db->mysql_insert_id();

它不是爲我工作。我用DB Driver作爲「mysql」。然後我安裝了「mysqli」,並在database.php中更改了DB驅動名稱,如
$db['default']['dbdriver'] = 'mysqli';
現在它對我來說工作正常。

+0

$ this-> db-> insert(table_name,$ data); return $ this-> db-> insert_id(); –

11

CodeIgniter的insert_id()將只返回一個insert()的ID。除非在調用函數之前執行類似$this->db->insert('table', $data);的操作,否則將無法返回ID。

+1

我得到它與以下更改工作。
1.我改變了dbdriver在config.php從MySQL使用下面的代碼
$this->db->mysql_insert_id();

+0

很明顯,我們所談論的後插入使用INSERT語句的一些值插入id來mysqli的
2。 –

+0

您從未發佈過代碼,所以我不確定您是否使用了活動記錄insert()。 –

1

假設你使用活動記錄模式 這應該工作
$this->db->insert_id()

4

只能使用此語法

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

return $last_id; 
1

我有同樣的問題,發現問題與此鏈接:http://kedyr.wordpress.com/2012/10/03/codeigniter-insert_id/

該解決方案不是一個合適的解決方案,因爲它只是一種通過使用本機sql來解決問題的方法,使用codeigniter方法「Query 「並處理原生的SQL回調。

$this->db->insert('references', $data); 
    $query = $this->db->query('SELECT LAST_INSERT_ID()'); 
    $row = $query->row_array(); 
    $LastIdInserted = $row['LAST_INSERT_ID()']; 
+0

在多用戶環境中,這個解決方案是一團糟! – meYnot

0

試試這個:的

$id = $this->db->insert_id() 

代替

$id = $this->db->mysql_insert_id(); 
2

請檢查您的表不具有自動遞增,一次場那麼$this->db->insert_id();將不會返回任何東西。

+0

在我的情況下,這種方法幫助我解決了這個問題。 –

+1

謝謝你Vignesh :) –

0

試試這個

$this->db->insert('table_name',$data); 
$id = $this->db->mysql_insert_id(); 
0

,如果你有這樣的代碼,你的代碼將工作:

var $table = 'your table name' 
$this->db->insert($this->table,$data1); 
     return $this->db->insert_id(); 

CodeIgniter的INSERT_ID()之前將只返回插入()的ID,如提,也不要忘記設置database.php中的DB驅動程序名稱,如

$db['default']['dbdriver'] = 'mysqli';