簡體   English   中英

如何從MySQL的函數向PHP返回單個值?

[英]How to return a single value from a function from MySQL to PHP?

我已經為此苦了一段時間了。 我根本無法返回單個值。 我可以很好地返回數組。 但不是一個單一的價值。 我有一個只有三列的數據庫,column1是userID,column2是friendID,column3是IfFriends,其值為0或1。

現在,如果我執行以下功能:

function CheckFriend($id, $friendid){
global $mysqli;

$stmt = $mysqli->prepare("SELECT IfFriends FROM friends WHERE userID=?
                          AND friendID=?");
$stmt->bind_param("ii", $id, $friendid);
$stmt->bind_result($IfFriends);
$stmt->execute();

    return $IfFriends;

現在我做錯了嗎? 我嘗試了SQL查詢,它可以正常工作,它給了我1。但是,如果我使用該函數,它給了我0。

在PHP中,我這樣寫:

$ iffriends = CheckFriend($ _ SESSION [“ id”],$ _REQUEST [“ friendid”]);

當我這樣做時:

回聲$ iffriends

無論如何,它總是給我回零。

我希望有人能夠花時間告訴我我做錯了什么。 先感謝您。

閱讀文檔

注意:

注意,所有列必須在mysqli_stmt_execute()之后和調用mysqli_stmt_fetch()之前綁定。 根據列類型,綁定變量可以靜默更改為相應的PHP類型。

因此, bind調用必須在execute之后進行,您將需要調用fetch讀取第一行。

// Parameters bound before execute
$stmt->bind_param("ii", $id, $friendid);

// Execute the statement
$stmt->execute();

// Result location bound (but this doesn't retrieve anything)
$stmt->bind_result($IfFriends);

// Fetch the first row of the result, stored into the result variable bound above
if($stmt->fetch())
{
  // Make sure you check the result of fetch().
  // If it returned false, no rows were returned.
  // In this case, it returned true, so your value is in $IfFriends
}

// If you happened to have multiple rows, you would call fetch again
// to retrieve the next row.
if($stmt->fetch())
{
  // You can continue calling fetch() until it returns false.
  // Most often this is done in a loop like:
  // while($stmt->fetch()) { /* Do something with the row */ }
}

您可以使用此函數獲取值。 這是一個PHP函數。 您只需使用具有單個返回值查詢的查詢來調用它。

function value_return($query){

$result= mysql_query($query);
$value=mysql_result($result,0);
return $value;

}

暫無
暫無

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

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