如何从 MySQL 到 PHP 的函数返回单个值


How to return a single value from a function from MySQL to PHP?

我已经为此苦苦挣扎了一段时间了。我根本无法返回单个值。我可以很好地返回数组。但没有一个值。我有一个只有三列的数据库,列 1 是用户 ID,列 2 是朋友 ID,列 3 是 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

无论如何,它总是给我一个0。

我希望有人能够花时间告诉我我做错了什么。提前谢谢你。

阅读文档:

注意:

请注意,所有列都必须绑定在 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;
}