So I'm trying to fetch data in a many-to-many relationship.
So far I have this, which finds the user:
$user = $_SESSION['user'];
$userID = mysql_query("SELECT * FROM users WHERE user='$user'") or die(mysql_error());
And I know that to echo this information I have to put it in an array like so:
while ($r = mysql_fetch_array($userID)) {
echo $r["0"];
}
This works fine, but when I try to find this variable in another table, I'm not sure what to use as the variable:
$projects = mysql_query("SELECT projects_ID FROM projects_users WHERE users_ID='???'") or die(mysql_error());
I've tried replacing ??? with $userID and $r, but to no avail. I know the code works because it's fine when I put a user ID in manually - where have I gone wrong?
解决方案
You can get your projects with one query:
$user = mysql_real_escape_string($_SESSION['user']);
$query = mysql_query("SELECT pu.projects_ID FROM users u
INNER JOIN projects_users pu ON (pu.users_ID = u.users_id)
WHERE u.user='$user'") or die(mysql_error());
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo $row['projects_ID'];
}