簡體   English   中英

PHP - MySQL從存儲過程中獲取out參數的值

[英]PHP - MySQL gets value of out parameter from a stored procedure

我使用mysqli從PHP調用了一個MySQL存儲過程。 這有一個輸出參數。

$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類型的對象作為數組

或者甚至只做一個"SELECT @id AS id"然后$row->id就可以了。 我總是重命名選擇列以在必要時保持名稱有意義:-)

順便說一下,您可以簡單地連接調用並選擇@ ...(帶有;語句分隔符),RS將是返回值。 不幸的是,這會返回一個mutli-resultset,你需要刷新整個set,否則后續查詢將停止。 請參閱以下示例:

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

或者將select添加到addNewUser並返回RS而不是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棧。

只需$row->{"@id"}就可以了。 您不能將stdClass用作數組( $row[0]... )。

另一種正確的方法,它的工作正常:干杯!

$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"};

    }
}

或者,您可以使用mysqli::fetch_assoc()將數據作為數組獲取,並使用$row['@id']訪問數據。

這是工作解決方案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM