我的functions.php文件中有几个函数。我想向函数添加查询,但是当我这样做时,它不起作用。它只是不显示查询的结果。当我将查询添加到主页并包含该功能时,它可以正常工作。
我包含配置文件,所以这不是问题。我也考虑了范围,所以我在函数中添加了GLOBAL $mysqli;
,但它仍然不起作用。知道这里的问题是什么吗?我宁愿在函数中包含查询,所以我不必将它们添加到主页面。
我的功能:
function friends($friendship) {
GLOBAL $mysqli;
$friendship = mysqli_query($mysqli,"SELECT * FROM friends WHERE friend_one = '$my_username' OR friend_one = '$username'
AND friend_two = '$username' OR friend_two = '$my_username'
AND invite_sent = 1 AND invite_accepted = 1 ");
if (mysqli_num_rows($friendship) == 1){
return true;
} else {
return false;
}
}
这是检查我是否是某人的朋友的部分。
<?php if (friends($friendship) == true) : ?>
We are friends hooray!
<?php endif; ?>
编辑#1 - 合并 因此,在将主页的代码与函数组合后,函数的外观如下:
function friends($friendship) {
$user_id = $_SESSION['user_id'];
//Zoek de username op van ingelogde user
$stmt = $mysqli->prepare("SELECT username, email FROM members WHERE user_id = ? ");
$stmt->bind_param('i', $user_id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($my_username, $my_email);
$stmt->fetch();
$stmt->close();
$username = $_GET["username"];
//Zoek de gebruiker en zijn/haar gegevens in de db
$stmt = $mysqli->prepare("SELECT user_id, gender, email, protected FROM members WHERE username = ? ");
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($userid, $gender, $email, $protected);
$stmt->fetch();
$stmt->close();
$friendship = mysqli_query($mysqli,"SELECT * FROM friends WHERE friend_one = '$my_username' OR friend_one = '$username'
AND friend_two = '$username' OR friend_two = '$my_username'
AND invite_sent = 1 AND invite_accepted = 1 ");
if (mysqli_num_rows($friendship) == 1){
return true;
} else {
return false;
}
}
答案 0 :(得分:1)
如何确保查询中的所有变量都可用?
function friends($friendship, $my_username, $username) {
//Added $my_username, $username to the function call
//since they are on the main page but not declared in the function otherwise
GLOBAL $mysqli;
$friendship = mysqli_query($mysqli, "SELECT * FROM friends WHERE (friend_one = '$my_username' OR friend_one = '$username')
AND (friend_two = '$username' OR friend_two = '$my_username')
AND (invite_sent = 1 AND invite_accepted = 1)") or die(mysqli_error($mysqli)); //Throw an error if the query fails
if (mysqli_num_rows($friendship) == 1){
return true;
} else {
return false;
}
}
我还要提醒不要使用GLOBAL,我会添加一些错误检查以帮助诊断问题。
<?php
//Add the variables here as well...
$friends = friends($friendship, $my_username, $username);
if($friends == true)
echo 'We are friends hooray!';
} else {
//Do something?
};
?>
答案 1 :(得分:0)
对于函数将使用的所有变量,如本例中的$ my_username,您必须在函数内声明和初始化它们,或者以参数的形式将它们传递给此函数,如@jason所描述的在答案中。
这些查询在您的主页上工作的原因是您的代码(查询)能够访问变量,因为它们是在特定范围内定义的。
由于此功能的朋友&#39;我不知道$ my_username是什么,你只需要在这个函数中定义变量或者以参数的形式传递它们。