繁体   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