I have two tables, a "users" and "updates" table. I want to grab these values from the tables:
id, username - from the "users" table message, createdOn - from the "updates" table
I need to grab these values for a specified user and friends of the user. I have already created an array containing all friends id's that would look like this:
array(1,3,7,21,45);
I need a query that will select all of the updates with an matching the previous array. The "updates" table also has a column "uid" which defines the user who posted the update. This is what I have so far:
$updates = "SELECT users.id, users.username, updates.message, updates.createdOn FROM users, updates WHERE updates.uid = '". $_COOKIE['id'] ."' ". $friendsNews ." ORDER BY updates.createdOn DESC LIMIT 0, 10";
$updates = mysql_query( $updates );
This isn't working for me though, I created a foreach loop that also creates an or statement which is inserted into the query "$friendsNews" that looks like this:
foreach( $myFriends as $fid ) {
$friendsNews .= " OR updates.uid = '". $fid ."'";
}
Once the entire query compiles the result of the query is this:
SELECT users.id, users.username, updates.message, updates.createdOn FROM users, updates WHERE updates.uid = '1' OR updates.uid = '2' OR updates.uid = '3' ORDER BY updates.createdOn DESC LIMIT 0, 10
If someone could help I would really appreciate it, I'm not very experienced with SQL join statements. Thanks!
Try
$sql = "SELECT users.id, users.username, updates.message, updates.createdOn, ".
" updates.message, updates.createdOn ".
" FROM users ".
" INNER JOIN updates ON updates.uid = users.id ".
" WHERE ".
" updates.uid IN ( ".implode(', ', $myFriends)." )";
I think that if you want to grab all updates for the users specified in the ids array, the simplest way would be to use a sql JOIN
and an IN
clause
select users.id, users.username, u1.message, u1.createdOn
from updates as u1
join users as u2 on u2.id = u1.uid
where u1.uid in(1,3,7,21,45)
order by u1.createdOn desc limit 0, 10;
Try this
if (in_array($_COOKIE['id'], $myFriends)) {
$flist = implode(',', $myFriends)
}else{
$flist = $_COOKIE['id'].','.implode(',', $myFriends); //if $_COOKIE['id'] is differed.....
}
$sql = "SELECT users.id, users.username, updates.message, updates.createdOn,
updates.message, updates.createdOn FROM users INNER JOIN updates
updates.uid = users.id WHERE updates.uid IN ( ".$flist." )";
Help for Logged user is differed.....