PHP-MySQL从存储过程获取out参数的值 [英] PHP - MySQL gets value of out parameter from a stored procedure
问题描述
我已经使用mysqli
从PHP调用了MySQL存储过程.它有一个out参数.
I have called a MySQL stored procedure from PHP using mysqli
. This has one out parameter.
$rs = $mysqli->query("CALL addNewUser($name,$age,@id)");
在这里,@id是out参数.接下来,我触发以下查询以获取out参数的值:
Here, @id is the out parameter. Next, I fire the following query to get the value of the out parameter:
$rs2 = $mysqli->query("SELECT @id");
while($row = $rs->fetch_object()){
echo var_dump($row);
}
var_dump
的输出如下.
object(stdClass)#5 (1) { ["@id"]=> string(6) "100026" }
因此,现在我想检索@id
的值,但我无法获取.我尝试了$row[0]->{@id}
,但这给出了以下错误:
So, now I want to retrieve the value of @id
, which I am unable to. I tried $row[0]->{@id}
but this gave following error:
PHP致命错误:不能将stdClass类型的对象用作数组
PHP Fatal error: Cannot use object of type stdClass as array
推荐答案
或者甚至只是执行"SELECT @id AS id"
,那么$row->id
都可以正常工作.我总是重命名选择列以使名称在必要时有意义:-)
Or even just do a "SELECT @id AS id"
then $row->id
will work fine. I always rename select columns to keep the name meaningful when necessary :-)
顺便说一句,您可以简单地将调用连接起来,然后选择@ ...(带有;语句定界符),RS将作为返回值.不幸的是,这将返回一个mutli-resultset,您需要刷新整个集合,否则后续查询将停止.请参阅以下示例:
BTW, you can simply concatenate the call and select @... (with a ; statement delimiter) and the RS will be the returned value. Unfortunately this returns a mutli-resultset and you need to flush the full set otherwise the subsequent queries will stall. See following examples:
$db->multi_query( "CALL addNewUser($name,$age,@id);SELECT @id as id" );
$db->next_result(); // flush the null RS from the call
$rs=$db->store_result(); // get the RS containing the id
echo $rs->fetch_object()->id, "\n";
$rs->free();
或者将选择添加到addNewUser中,然后返回一个RS而不是out参数
Alternatively add the select into the addNewUser and return a RS instead of out param
$rs = $db->query( "CALL addNewUser($name,$age)" );
echo $rs->fetch_object()->id, "\n";
$rs->close();
$db->next_result(); // flush the null RS from the call
第一个返回一个多查询(NULL,RS)集,第二个返回一个(RS,NULL)集,因此您可以使用一个简单的query()调用来嵌入第一个fetch_object(),但是您仍然需要刷新RS堆栈.
The first returns a multiquery (NULL, RS) set and the second a (RS, NULL) set, hence you can use a simple query() call which embeds the first fetch_object(), but you still need to flush the RS stack.
这篇关于PHP-MySQL从存储过程获取out参数的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!