質問

I have an ID field of type int that auto increments whenever I insert a row.

Is mysql_insert_id() gets the inserted row when I do this

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

I was wondering if it will get the ID when calling a stored proc.

役に立ちましたか?

解決

If you're using a stored procedure then you have no real access to what's going on in that procedure unless the procedure itself passes the information out. You can, therefore, define an OUT parameter to the procedure and return the last_insert_id() value in that:

Procedure

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 ;

Call with a mysqli query

call p(@InsertId);

Then retrieve the result with another mysqli query

select @InsertId as id;

Note - the variables live for the life of the connection so unless you close the connection you can retrieve the value of @InsertId whenever it's convenient.

Thanks to Patchrick for adding the PHP niceties:

$acct = mysql_query("call p(@InsertId);select @InsertId as id;");
$row = mysql_fetch_array($acct);
echo $row["id"]; 
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top