0

This is my friendship table:

mysqli relationship table

How can I query removing my own id? I'm user_id = 1 How can I print my friends? (2, 3 and 5)

$showFriends = $mysqli->query("SELECT * FROM `relationship` WHERE (`user1_id` = '$user_id' OR `user2_id` = '$user_id') AND `status` = 1") or die(mysqli_error($mysqli));
    if($showFriends->num_rows > 0) {
        while($f = $showFriends->fetch_assoc()) {
            foreach(($f !== $user_id) as $como) {
                $como = $f;
            }
        }
        echo $como;
    } else {
        echo "You have no friends!";
    }

Kinda blocked now :(

Ruth
  • 11
  • 4
  • `WHERE user1_id != MY_ID AND user2_id != MY_ID`? – Darren Feb 05 '17 at 23:41
  • have you attempted anything? Are you wanting to return that csv as a mysql result, or through formatting in php? – Sean Feb 05 '17 at 23:41
  • @Darren probably the right idea, but that specifically would not work. – Sean Feb 05 '17 at 23:43
  • Darren it can't be that way because I can be in either column.. Maybe I should think to alter the table. Make an new one... – Ruth Feb 05 '17 at 23:45
  • Don't post your code in a comment. [Edit](http://stackoverflow.com/posts/42058601/edit) your question and put your code there. – Sean Feb 05 '17 at 23:47
  • @Sean I know ;P we aren't a charity here haha (*was purely pseudo code*) – Darren Feb 05 '17 at 23:50
  • Done! Sorry :) Gotta keep that in mind – Ruth Feb 05 '17 at 23:50
  • @Ruth How do you define the relationship? Does user1 always add user2? – Darren Feb 05 '17 at 23:51
  • Darren not true.. Simply don't know how to do it. If you wanna check my code you can see the project in http://dicasparaapostas.com – Ruth Feb 05 '17 at 23:51
  • Darren, saw this here: http://www.codedodle.com/2014/12/social-network-friends-database.html – Ruth Feb 05 '17 at 23:53
  • 1
    @Darren, doing pseduo code is completely valid, but it should be a plausible example. – Sean Feb 05 '17 at 23:53

1 Answers1

1

Simplify your logic. You only need to check if if($como != $user_id).

Try something like -

$showFriends = $mysqli->query("SELECT * FROM relationship WHERE (user1_id = '$user_id' OR user2_id = '$user_id') AND status = 1") or die(mysqli_error($mysqli)); 
if($showFriends->num_rows > 0) { 
    while($f = $showFriends->fetch_assoc()) { 
        foreach($f as $como) { 
            if($como != $user_id){
                echo $como;
            } 
        }
}
else { 
    echo "You have no friends!";
}

we assume that you have properly sanitized $user_id to prevent sql injection. If not, make sure to visit How can I prevent SQL injection in PHP?

Community
  • 1
  • 1
Sean
  • 12,443
  • 3
  • 29
  • 47
  • Well I only do this to sanitize data: $id = strip_tags(htmlentities(htmlspecialchars($id))); Not sure what SQL Injection is.. – Ruth Feb 06 '17 at 00:20