2012-05-08 22 views
8

我正在使用Postgresql,當我想使用PDO檢索最新插入ID時,出現問題。這裏是我的代碼:lastInsertId在Postgresql中不起作用

$db->lastInsertId('columnName'); 

錯誤消息說

SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "columnName" does not exist 

我想我對PHP手冊中指出,「序列對象」的一些誤解。

Note: 

Returns the ID of the last inserted row, or the last value from a sequence object, 
depending on the underlying driver. For example, PDO_PGSQL() requires you to specify the 
name of a sequence object for the name parameter. 

當前,「columnName」是該自動遞增屬性的字符串。任何人都可以指出我出錯的地方嗎?謝謝。

+1

[在PDO準備插入後獲取最後一個插入id]的可能重複(http://stackoverflow.com/questions/5057954/get-last-insert-id-after-a-prepared-insert-with-pdo ) –

回答

15

PostgreSQL使用sequencesserial列生成值,serial列通常用於PostgreSQL中的「自動遞增」列。序列具有名稱,並且通常獨立於任何特定的表,因此您可以使用一個序列爲多個不同的表生成唯一的ID;該序列的名字是什麼lastInsertId希望作爲它的參數:

例如,PDO_PGSQL()需要您爲參數指定序列對象的名稱。

PostgreSQL所創建的序列對象自動命名爲[table]_[column]_seq,所以:

$id = $db->lastInsertId('tableName_columnName_seq'); 
+5

不會那樣工作。 PGSQL「需要」一個參數來表示序列對象。如果您將其留空,則不會返回任何內容。 – Michael

+3

@Michael:那麼你需要知道序列的名稱。缺省值是't_c_seq',其中't'是表名,'c'是列名。不過這個要求很奇怪。我沒有所有的PHP/PostgreSQL設置ATM,所以我無法驗證這一點。 –

+0

table_column_seq,就是這樣!謝謝! – Michael

-1

使用序列名稱,而不是列名

$db->lastInsertId('columnName'); 
3

我今天就遇到了這個問題,lastInsertId()是隻返回false。研究發現,解決在不同的線程我的問題的答案:https://stackoverflow.com/a/31638196/1477123

CREATE TABLE ingredients (
    id   SERIAL PRIMARY KEY, 
    name  varchar(255) NOT NULL, 
); 

所以序列名稱將是ingredients_id_seq

$db->lastInsertId('ingredients_id_seq'); 
1

所以序列名ingredients_id_seq

$db->lastInsertId('ingredients_id_seq'); 

這種格式實際上解決了我的問題!

+0

你也可以使用$ db-> nextval(); –

相關問題