我的网站上有一项功能,让彼此结识的用户可以查看彼此的照片。例如,如果我以Conor
登录,并且我想查看Alice's
张照片,Conor必须与Alice成为朋友,而Alice必须与Conor成为朋友 - 他们必须是共同的朋友。
我的数据库中有一个名为favourites
的表 - 它存储了所有好友请求。假设favourites
有两行:
id: 1
favourited_who: Alice
favourited_by: Conor
id: 2
favourited_who: Conor
favourited_by: Alice
他们彼此都有favourited
。
请考虑以下代码段:
<?php
$get_favs_q = mysqli_query ($connect, "SELECT * FROM favourites");
$getting_favs = mysqli_fetch_assoc($get_favs_q);
$user_favourited = $getting_favs['favourited_who'];
$user_favourited_by = $getting_favs['favourited_by'];
/*************************/
if ($user == $username || $user_favourited == $user && $user_favourited_by == $username
|| $user_favourited == $username && $user_favourited_by == $user){
// $user = name in the URL after ?= - As we are on Alice's page .. $user equals Alice
// $username = session variable for logged in user - $username = Conor
// If both users have each other favourited, then the code to display images appears here.
} else {
echo " <span style='margin-left: 10px;'>
You and $ufirstname must favourite each other to view each others backstage.
</span>";
}
?>
我已经涵盖了所有情景,以检查$user
是否有利于$username
,反之亦然,但是,else语句总是被执行,回应消息而我没有&# 39;不明白为什么。
答案 0 :(得分:2)
在支票周围添加括号,如下所示:
if (
$user == $username
|| ($user_favourited == $user && $user_favourited_by == $username)
|| ($user_favourited == $username && $user_favourited_by == $user) ){
// Do your thing
} else {
// Do the other thing
}
问题在于&#34; ands&#34;永远都是假的,所以整个陈述总是假的。您可以将您的陈述缩短为以下内容:
A or B and C or D and E
逻辑上与
相同A or B or D and C and E
从C = !E
开始,语句总是错误的。你真正想要的是什么,我上面展示的是:
A or (B and C) or (D and E)