Im trying to grab all the users status from my website. Here is my table
If i add another user my username gets added into user1 If another user adds me there username gets added into user1 and mine into user2
So i need to try and grab all the ids from user1 and user2 were accepted is 1
which i do like so
$id = $_SESSION['user_id'] ;
$yes = '1';
$query = $db2->prepare("SELECT * FROM friend_requests WHERE (user1='".$id."' OR user2='".$id."') AND accepted = '".$yes."'");
$query->execute();
foreach ($query as $row) {
print $row['user1'] . "\t";
print $row['user2'] . "\t";
}
But now i have $row['user2'] and $row['user1'] is there any way of putting these together into one ? So i can simply do a pdo loop select status were id = that ?
Im trying to grab all status were id = $row['user1'] or $row['user2'] but i dont want to use or in my pdo select.
You could edit your SQL as follows:
"SELECT id, (CASE WHEN user1 = $id THEN user2 ELSE user1 END) as user, time FROM friend_requests WHERE (user1 = $id OR user2 = $id) AND accepted = 1"
This will return just the accepted friends for your user with id $ID.
Proof of concept here: http://www.sqlfiddle.com/#!9/e0b337/2
EDIT: As has been pointed out, you should bind parameters to protect against SQL injection, but that's outside the scope of your question.
EDIT 2: Per your second question below you can either do two loops or, if the table is small relative to available memory, you can do a fetchAll() as follows.
$id = $_SESSION['user_id'] ;
$query = $db2->prepare("SELECT (CASE WHEN user1 = :userid THEN user2 ELSE user1 END) as user FROM friend_requests WHERE (user1 = :userid OR user2 = :userid) AND accepted = 1");
$query->bindParam(':userid', $id, PDO::PARAM_INT);
$query->execute();
$friends = $query->fetchAll(PDO::FETCH_ASSOC);
$friends[] = array('user'=>$id);
foreach ($friends as $k=>$friend) {
echo $friend . "\t";
}
You can use UNION
:
<?php
$id = $_SESSION['user_id'] ;
$yes = '1';
$query = $db2->prepare("SELECT id,user2 AS `user` FROM `friend_requests` WHERE user1=:user1 AND accepted={$yes} UNION SELECT id,user1 AS `user` FROM `friend_requests` WHERE user2=:user2 AND accepted={$yes}");
$query->bindParam(':user1', $id, PDO::PARAM_INT);
$query->bindParam(':user2', $id, PDO::PARAM_INT);
$query->execute();
foreach ($query as $row) {
print $row['user'] . "\t";
}
Example: sqlfiddle