PDA

View Full Version : Selecting data from one table based on data in another


weemee500
10-20-2009, 10:54 AM
Hi, I am currently trying to make a part for my user driven website where one user can subscribe to another and whoever they have subscribed to is echoed back on there profile page.

my users table structure is: id username password and my subscription table is: id user_id follow_id

i am currently trying to query the logged in users subscriptions with this sql_query

$subsQuery = mysql_query("SELECT U.username FROM users AS U INNER JOIN subscription AS Sub.follow_id=U.id WHERE Sub.user_id=".$ID); $ID being the logged in users id.

However when trying to echo this on the page using this bit of php:

<? while ($subs = mysql_fetch_assoc($subsQuery)) { ?><br /><br />
<? echo $subs['username'] ?>

<? } ?>

it throws back this error:

Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/avince/public_html/users/user.php on line 53

Any help would be much appreciated!

abduraooft
10-20-2009, 11:42 AM
$subsQuery = mysql_query("SELECT U.username FROM users AS U INNER JOIN subscription AS Sub.follow_id=U.id WHERE Sub.user_id=".$ID); Your query is incorrect. You should always add proper error checks to your query, like
mysql_query(....) or die(mysql_error());

Old Pedant
10-20-2009, 07:44 PM
And *PROBABLY* you meant to use the query:
// always build the query in a separate string variable, thus:
$sql = "SELECT U.username "
. " FROM users AS U INNER JOIN subscription AS Sub "
. " ON Sub.follow_id = U.id "
. " WHERE Sub.user_id = " . $ID;

// so you can dump that out for debugging (comment out the debug when it works)
echo "DEBUG SQL: " . $sql . "<HR>\n";

$subsQuery = mysql_query( $sql ) or die(mysql_error());
...