2014-01-27 156 views
0

我試圖在數據庫中插入2行,第二行需要第一行的自動遞增ID。 我已經與LAST_INSERT_ID()測試,但我有一個MysqlIntegrityConstraintViolationException如何使用MySQL獲取最後一個ID插入

Cannot add or update a child row : a foreign key constraint fails ('customer_user_role', CONSTRAINT 'fk_customer_user_role_customer_id' FOREIGN KEY ('customer_user_role_id') REFERENCES 'customer' ('customer_id') ON DELETE NO ACTION ON UPDATE NO ACTION)

我的SQL請求是:

sqlu"INSERT INTO customer (name, email, phone, isActivated) VALUES ($name, $email, $phoneNumber, $isActivated)"

sqlu"INSERT INTO customer_user_role (customer_id, user_id, customer_roletype_id) VALUES (LAST_INSERT_ID(), $userId, $roleTypeId)"

(我的工作寬度播放&油滑所以這爲什麼特定語法)

當我在PhpMyAdmin上執行此操作時,會顯示相同的錯誤,我不知道如何繼續...

回答

0

請看看這個http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html。在插入第二行之前,獲取該id並繼續。不應該很難。

+0

我已經看過這個文檔,它使我錯誤,用'last_insert_id()'和'mysql_insert_id()' – Azuken

+0

你調試過嗎?首先調試看看你是否真的獲得了價值。您的列是否設置爲自動增量? – johnny

+0

當我從PHPMyAdmin執行時,它返回我0 ...插入課程後。 – Azuken

0

嘗試這種情況:

 set @last_inserted_id = LAST_INSERT_ID(); 

然後使用@last_inserted_id作爲值而插入到另一個表。

+0

我試過了,它不起作用,也許是因爲光滑的語法 – Azuken

相關問題