Database:
- xx_users (id, name, user_id, email, location)
- xx_questions (id, question, description, user_id)
Original code:
$friends = $facebook->api('/me/friends');
$arr= $friends['data'];
$friend_ids_arr = array();
foreach($arr as $friend) {
$friend_ids_arr[] = $friend['id'];
}
$sql = "SELECT * FROM xx_questions WHERE user_id IN (" . implode(',', $friend_ids_arr) . ") OR user_id = '$user' ORDER BY time DESC";
New code:
$friends = $facebook->api('/me/friends');
$arr= $friends['data'];
$friend_ids_arr = array();
foreach($arr as $friend) {
$friend_ids_arr[] = $friend['id'];
}
$sql = "SELECT *
FROM xx_questions q JOIN xx_users u ON
q.user_id = u.user_id
WHERE q.user_id IN (implode(',', $friend_ids_arr)) OR // STEP 1
q.user_id = '$user' OR // STEP 2
u.location = (SELECT location FROM xx_users WHERE user_id = $user) // STEP 3
ORDER BY q .time DESC";
$data = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($data)) {
echo $row[id];
}
I am trying to select questions from xx_questions (that have been posted by users) should any of three situations arise:
- Those values where the poster’s user_id matches that of one of the current user’s friends (i.e. the poster and the user are friends)
- Those values where the poster’s user_id matches that of the user (i.e. the poster is the user)
- Those values where the poster’s location matches that of the current user (i.e. the poster and user are currently in the same city)
I had originally achieved steps 1 and 2, but when I add step 3, two things happen:
- Step 1 stops working (i.e. only posts from the current user and people in the same city are returned)
- The
$row[id]echoed in the while loop is that of xx_users, not xx_questions. I’ve tried$row[q.id]but to no avail.
Any idea what’s gone wrong?
In your seconds query your implode statement isnt outside the string.
While php can add variable to a double quoted string (
$x = "test $test test"$test will be changed to the value of $test) it can’t escape functions. So this would return inYou should use:
And in the end you are using
SELECT *and if both tables have an Id column, only one is returned. Its better to useSELECT q.*to get only the questions row or perhapsSELECT q.*, u.locationto get the entire question row and the location from the user table.I also checked your query and it should do what you want
The only thing I changed is the
implodeand remove the ” around$user. That is incase the $user isnt actualy an integer but a string containing a number, but has some extra spaces appended (eg ‘1 ‘ instead of ‘1’);