2014-05-07 71 views
1

我有一個int類型的ID字段自動遞增,每當我插入行獲得ID。PHP/MySQL的插入,然後通過調用存儲過程

mysql_insert_id()當我做這個

mysql_query("call AddUser($user,$pass);"); 

我在想,如果調用存儲過程時,它會得到ID獲取插入的行。

+0

這可能會有所幫助:http://stackoverflow.com/a/3143038/2518525 – Darren

+0

感謝,這給了我最關鍵的線索,它是LAST_INSERT_ID()對於MySQL,相同SCOPE_IDENTITY() – Patchrick

回答

2

如果你使用存儲過程,那麼你必須除非程序本身傳遞出的信息是怎麼回事在該過程沒有真正的訪問。你可以,因此,定義一個OUT參數的程序和返回的LAST_INSERT_ID()值:

程序與mysqli的查詢

call p(@InsertId); 

delimiter $$ 
drop procedure if exists p$$ 
CREATE PROCEDURE p(OUT InsertId int) 
BEGIN 
insert test.Numbers (Numbers) values (3); 
select last_insert_id() into InsertId ; 

END$$ 
delimiter ; 

呼叫然後用另一mysqli的查詢

檢索結果
select @InsertId as id; 

注 - 變量活連接的生活所以,除非你關閉連接,你可以檢索@InsertId的價值時,它的方便。

感謝Patchrick用於添加PHP禮節:

$acct = mysql_query("call p(@InsertId);select @InsertId as id;"); 
$row = mysql_fetch_array($acct); 
echo $row["id"]; 
+0

因此使用在PHP時,$ ACCT =請求mysql_query( 「呼叫p(@InsertId);選擇@InsertId爲ID;」); $ row = mysql_fetch_array($ acct); echo $ row [「id」]; – Patchrick

+0

@patchrick謝謝 - 我已將它編輯到我的答案中。 –

+0

僅供參考 - 我發現我需要執行「select @InsertId as id;」在PHP7中使用mysqli作爲單獨的MySQL查詢調用。 – mnutsch