PHP - MySQL的失控参数的值从存储过程(PHP - MySQL gets value

2019-06-26 14:17发布

我呼吁从PHP中使用MySQL的存储过程mysqli 。 这有一个输出参数。

$rs = $mysqli->query("CALL addNewUser($name,$age,@id)");

在这里,@id是out参数。 接下来,我火了以下查询来获取out参数的值:

$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}但是这给了以下错误:

PHP致命错误:无法使用类型stdClass的对象为数组

Answer 1:

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 :-)

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();

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

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.



Answer 2:

只需$row->{"@id"}将在这里工作。 你不能使用stdClass一个数组( $row[0]... )。



Answer 3:

另一种方法正确以其优良的工作:干杯!

$procedureName = 'VALIDATE_USER';
$procedure = "CALL $procedureName('$username','$pwd',@p_userid)";
$results1 = $dbconnection->query($procedure);
$results2 = $dbconnection->query("SELECT @p_userid");
$num_rows = $results2->num_rows;
if ($num_rows > 0) {

    while($row = $results2->fetch_object())
    {
    echo $row->{"@p_userid"};

    }
}


Answer 4:

或者,你可以直接获取数据,使用数组mysqli::fetch_assoc()和访问使用数据$row['@id']



Answer 5:

这里是工作的解决方案:

enter code $res = $conn->multi_query( "CALL PROCNAME(@x);SELECT @x" );
if( $res ) {
  $results = 0;
  do {
    if ($result = $conn->store_result()) {
      printf( "<b>Result #%u</b>:<br/>", ++$results );
      while( $row = $result->fetch_row() ) {
        foreach( $row as $cell ) echo $cell, "&nbsp;";
      }
      $result->close();
      if( $conn->more_results() ) echo "<br/>";
    }
  } while( $conn->next_result() );
}
$conn->close();


文章来源: PHP - MySQL gets value of out parameter from a stored procedure