我有三个这样的表:
表 1:
id|name with row 1: [1|alex] and row2: [2|jane]
表2
nameid|classid with row 1: [1|2] and row2: [1|1] and row3: [2|2]
表 3
classid|classname with row 1: [1|A] and row2: [2|B]
我想获取表 1 中的 ID,将其与表 2 进行比较以获取类 ID,然后将它们与表 3 进行比较以获取类名。我有表 1 中的 ID,我这样做:
<?php
$result = mysql_query("SELECT * FROM table2 WHERE nameid='$id'") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$classid = $row['classid'];
//Get the class id to compare with table3
$result = mysql_query("SELECT * FROM table3 WHERE classid='$classid'") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo $row['classname'];
//Write down the class name
}
}
?>
但是在表2中,有两行(1和2)具有相同的nameid = 1
,但是代码只打印了一个类名。
最佳答案
您正在重复使用导致问题的 $row
和 $result
。
$result = mysql_query("SELECT * FROM table2 WHERE nameid='$id'") or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$classid = $row['classid'];
$result2 = mysql_query("SELECT * FROM table3 WHERE classid='$classid'")or die(mysql_error());
while($row2 = mysql_fetch_array($result2)){
echo $row2['classname'];
}
}
但是,您可以通过连接在一个查询中获得它。
select table3.classname from table2 left join table3 on table3.classid = table2.classid where table2.nameid='$id'
还必须将其放入,否则其他人不会使用 mysql_* 函数,您应该使用 mysqli 或 pdo。
关于php - 从mysql获取数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15280392/