2012-07-27 183 views
3

我使用mysqli從PHP調用了一個MySQL存儲過程。這有一個輸出參數。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 Fatal error: Cannot use object of type stdClass as array

回答

6

甚至只是做一個"SELECT @id AS id"然後$row->id將正常工作。我總是選擇重命名列,以保持名稱有意義必要時:-)

順便說一句,你可以簡單地拼接呼叫,並選擇@ ......(用;語句分隔符)和RS將返回值。不幸的是,這會返回一個mutli結果集,你需要刷新整個集合,否則隨後的查詢將停止。見以下實施例:

$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函數並返回,而不是出PARAM一個RS

$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 

第一返回設定multiquery(NULL,RS)和第二一個(RS ,NULL)set,因此你可以使用一個簡單的query()調用來嵌入第一個fetch_object(),但你仍然需要刷新RS棧。

+0

嗨,請您詳細說明您提供的第二條建議。謝謝:) – mtk 2012-07-28 12:56:03

+0

@mtk,對不起,我應該檢查BTWs與我的代碼:-(我使用第二個版本 – TerryE 2012-07-28 14:53:53

+0

嘿,非常感謝解釋,所有的例子工作得很好,只是尋找一個解決方案,但得到了三個: ) – mtk 2012-07-28 15:10:20

4

只是$row->{"@id"}將在這裏工作。您不能使用stdClass作爲數組($row[0]...)。

+1

你需要引用的列名,以避免和通知等。 '@ id'變成''id''(除非你有一個名爲'id'的定義常量)。 – cHao 2012-07-27 18:13:25

+0

@cHao:已更正。 – 2012-07-27 18:17:09

+0

@cHao。@ MadaraUchiha @ [email protected] – mtk 2012-09-19 06:11:00

2

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

2

另一種正確的方法其工作正常:乾杯!

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

    } 
} 
0

這裏是工作的解決方案:

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