PHP第二个while循环内的while循环只运行一次

时间:2016-08-31 09:10:34

标签: php mysql while-loop

我的php / mysql编码需要一些专家帮助。我希望我的while循环检查每个块,并通过使用第二个while循环来完成它,从1行中的同一块中回显出所有用户。我设法显示它,但它不会分别显示其他块中的其他用户。

到目前为止,这是我的代码,虽然我对php很新。

<html>
<head>
</head>
<body>
    <table border='1'>
        <th>Block</th>
        <th>company</th>
        <th>Username</th>
        <th>datetime</th>
    <?php
    require('db.php');


    $sql = "
    SELECT block_directories.block, event_details.username, event_details.datetime, event_details.eventDate, companies.company, event_details.tag
    FROM block_directories INNER JOIN event_details
    ON block_directories.block_id = event_details.tag
    INNER JOIN companies
    ON event_details.company=companies.company_id"
    ;
    $records=mysql_query($sql);

    $sqlblock = "
    SELECT * FROM block_directories"
    ;
    $blockrecords=mysql_query($sqlblock);

    //while loop to echo all blocks into table ina column
    while($blkrecords=mysql_fetch_assoc($blockrecords)){    
        echo "<tr>";
        echo "<td>{$blkrecords['block']}</td>";

        //while loop to echo all users within the same block
        while($users=mysql_fetch_assoc($records)){
            if($users['block']==$blkrecords['block']){
                echo "<td>{$users['company']}</td>";
                echo "<td>{$users['username']}</td>";
                echo "<td>{$users['datetime']}</td>";
            }
        }
        echo "</tr>";
    }
    ?>
    </table>
</body>

Output Display of the code

1 个答案:

答案 0 :(得分:0)

这是因为mysql_fetch_assoc()在指针到达结果集的末尾后没有返回行。

您需要通过添加以下行将其重新指向结果集的第一个。

mysql_data_seek($records, 0);

所以你的循环代码会是这样的,

while($blkrecords=mysql_fetch_assoc($blockrecords)){    
        echo "<tr>";
        echo "<td>{$blkrecords['block']}</td>";

        //while loop to echo all users within the same block
        while($users=mysql_fetch_assoc($records)){
            if($users['block']==$blkrecords['block']){
                echo "<td>{$users['company']}</td>";
                echo "<td>{$users['username']}</td>";
                echo "<td>{$users['datetime']}</td>";
            }
        }
        mysql_data_seek($records, 0);
        echo "</tr>";
    }
  

mysql_ *扩展在PHP 5.5.0中已被弃用,并且已被删除   PHP 7.0.0。相反,应该使用MySQLi或PDO_MySQL扩展。