Reputation: 867
I have a feature on my site where users who have befriended each other can view each others photos. For example, if I am logged in as Conor
, and I want to view Alice's
photos, Conor must befriend Alice, and Alice must befriend Conor - they must be mutual friends.
I have a table in my database called favourites
- which stores all friend requests. Lets assume favourites
has two rows:
id: 1
favourited_who: Alice
favourited_by: Conor
id: 2
favourited_who: Conor
favourited_by: Alice
They both have each other favourited
.
Consider the following snippet:
<?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>";
}
?>
I have covered all scenario's to check whether the $user
has favourited the $username
and vice versa, but, the else statement is always being executed, echoing the message and I don't understand why.
Upvotes: 0
Views: 42
Reputation: 2626
Add parenthesis around your checks like so:
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
}
The problem is that one of the "ands" is always going to be false, so the whole statement is always false. You can shorten your statement to the following:
A or B and C or D and E
Which is logically the same as
A or B or D and C and E
And since C = !E
, the statement is always false. What you really want, and what I showed above is:
A or (B and C) or (D and E)
Upvotes: 2