php - 从mysql获取数据库

标签 php mysql database

我有三个这样的表:

表 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/

相关文章:

php - 如果一列有多个关键字,我如何从数据库中获取结果?

sql-server - 默认 SQL Server 端口

php - BigCommerce Webhook 未触发

javascript - 如何在下拉表单中添加 onchange 函数来发送数据?

PHP 相当于 Python 的 struct

mysql - 使用 laravel 查询生成器根据相关表排序结果

php txt 文件转成 sql

php - 我怎样才能确保 PHP 正在使用 TBinaryProtocolAccelerated

mysql - Laravel:未找到基表或 View :1146 表不存在

mysql - 显示带有类别的产品列表不会显示未耦合的类别