PHP从MySQL数据库中获取数据
问题描述:
所以我试图以多对多关系获取数据.
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());
我尝试更换??? $ userID和$ r,但无济于事.我知道代码有效,因为手动输入用户ID很好-我哪里出错了?
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'];
}