如何使用两个while循环检索数据

时间:2017-04-07 14:25:08

标签: php

第一个查询工作正常,它检索类ID,但我第二个查询有问题,因为它没有检索子名称

<select name="child-name" id="Schild">
<?php
    $username = $_SESSION['username'];
    $sql1 = "SELECT Class_id FROM Class WHERE Emp_id = '$username'";
    $result = mysqli_query($database,$sql) or die(mysqli_error($database));

    while($row = mysqli_fetch_array($result))
    {
        $classID = $row['Class_id'];
        $sql2 = "SELECT Name FROM Children WHERE Class_id = '$classID'";
        $result2 = mysqli_query($database,$sql2) or die(mysqli_error($database));
        while($row = mysqli_fetch_array($result2))
?>
    <option><?php echo $row['Name'];?></option>  

<?php 
        }
?> 
</select>

1 个答案:

答案 0 :(得分:1)

您在两个结果集提取中都使用$ row。因此,为外环破坏它

虽然测试总是添加这些行,特别是如果您在实时/托管服务器上进行测试,几乎肯定会关闭错误报告

<?php
    ini_set('display_errors', 1); 
    ini_set('log_errors',1); 
    error_reporting(E_ALL); 
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
?>

<select name="child-name" id="Schild">
<?php
    $username = $_SESSION['username'];
    $sql1 = "SELECT Class_id FROM Class WHERE Emp_id = '$username'";
    $result = mysqli_query($database,$sql1) or die(mysqli_error($database));
    // Late breaking fix             ^^^^

    while($row = mysqli_fetch_array($result))
    {
        $classID = $row['Class_id'];
        $sql2 = "SELECT Name FROM Children WHERE Class_id = '$classID'";
        $result2 = mysqli_query($database,$sql2) or die(mysqli_error($database));
        while($row2 = mysqli_fetch_array($result2)) {
    // fix    ^^^^^
?>
    <option value="<?php echo $row2['Name'];?>"><?php echo $row2['Name'];?></option>  
<?php 
    // fix             ^^^^^
        }
?> 
</select>
<?php
    // also add terminator for first while loop
    }
?>