php - 如何在 While 语句中运行 While 语句以从数据库中获取值?

标签 php mysql phpmyadmin mysql-management

这是我的功能:

        $result_display = mysql_query("SELECT * FROM Events ORDER BY TimeStamp DESC LIMIT $y, 20");
        $result_comment = mysql_query("SELECT * FROM Comments");


while($row_display = mysql_fetch_array($result_display)){
    echo "<div id='id'" . $row_display['ID'] . " class='eventdiv' data-sort='".$row_display['TimeStamp']."'>".$row_display['Title']." TIME: ".$row_display['TimeStamp']."</div>";

    while($row_comment = mysql_fetch_array($result_comment)){
        echo $row_comment['com_details'];
    }

}

HTML 输出类似于:

<div id='id12' class='eventdiv' data-sort='238781>Time: 238781</div>
<div id='id13' class='eventdiv' data-sort='238784>Time: 238784</div>
<div id='id14' class='eventdiv' data-sort='238785>Time: 238785</div>
<div id='id15' class='eventdiv' data-sort='238789>Time: 238789</div>
<div id='id16' class='eventdiv' data-sort='238791>Time: 238791</div>
<div id='id17' class='eventdiv' data-sort='238795>Time: 238795</div>

These are the comment details...

但我希望输出是这样的:

<div id='id12' class='eventdiv' data-sort='238781>Time: 238781</div>

These are the comment details...

<div id='id13' class='eventdiv' data-sort='238784>Time: 238784</div>

These are the comment details...

<div id='id14' class='eventdiv' data-sort='238785>Time: 238785</div>

These are the comment details...

<div id='id15' class='eventdiv' data-sort='238789>Time: 238789</div>

These are the comment details...

<div id='id16' class='eventdiv' data-sort='238791>Time: 238791</div>

These are the comment details...

<div id='id17' class='eventdiv' data-sort='238795>Time: 238795</div>

These are the comment details...

我认为我在 while 语句中包含 while 语句的方式会像上面的 HTML 一样显示它,但事实并非如此。

最佳答案

在您第一次运行 $result_comment 结果后,您必须使用 mysql_data_seek( $result_comment ) 重置它。所以:

while($row_display = mysql_fetch_array($result_display)){
    echo "<div id='id'" . $row_display['ID'] . " class='eventdiv' data-sort='".$row_display['TimeStamp']."'>".$row_display['Title']." TIME: ".$row_display['TimeStamp']."</div>";

    while($row_comment = mysql_fetch_array($result_comment)){
        echo $row_comment['com_details'];
    }

    mysql_data_seek( $result_comment );

}

关于php - 如何在 While 语句中运行 While 语句以从数据库中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6351416/

相关文章:

php - 用于从分层数组生成平面(但带有嵌套标题)数组的递归函数

mysql - 修复大型 MyISAM 数据文件

mysql - 从单个查询中的三个表中计数?

mysql - 不支持 SQL 重复列名

php - phpmyadmin 中的错误 - `mysqli extension is missing`

php - 无法增加文件上传大小 WAMP

php - 尝试数据库导出会产生找不到网页错误

php - 如何在不使用 ajax 重新加载的情况下提交我的表单?

php - 使用 PHP 的 file_get_contents 后将类添加到 SVG 元素

php - 使用PHP从数据库中检索多个图像