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

到目前为止,这是我的代码,不过我对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

最佳答案

这是因为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扩展。

10-05 21:01
查看更多