繁体   English   中英

以HTML格式显示多个PHP查询结果

[英]Display multiple PHP query results in HTML

所以有以下while循环,它将输出在PHP中执行的SQL查询的所有结果:

while ($row = mysqli_fetch_array($result)) 
{
    $restaurant_name = $row['restaurant_name'];
    $cusine = $row['cusine'];
    $wait_time = $row['wait_time'];
    $output = "Resturant Name: $restaurant_name <br /> Cusine: $cusine <br /> Average Wait Time: $wait_time";
    echo "$output";
}

您可以假设$result将包含我一次在行中读取的表。 上面的代码工作得很好,但是当我尝试用HTML显示信息时(实际上它看起来不错)我遇到了一个问题

如果我执行以下操作:

<html>              
<section id="main" class="container 75%">

    <header>
        <h2>Here Are Some Places You'd Like To Eat</h2>
    </header>

    <div class="box">
    <?php echo $output; ?>
    </div>
</section>
</html>

它只会显示最后的手段。 我知道发生这种情况是因为$output一次只能容纳一个字符串,但我不知道在HTML上显示信息的任何其他方式。 我虽然可能使用数组来存储所有字符串,但文档没有告诉我如何设置动态数组。

这里有没有人知道如何在HTML页面中显示搜索查询的所有结果?

您可以将php和html代码组合在一起,如下所示:

<header>
    <h2>Here Are Some Places You'd Like To Eat</h2>
</header>

<?php
while ($row = mysqli_fetch_array($result)) :
    $restaurant_name = $row['restaurant_name'];
    $cusine = $row['cusine'];
    $wait_time = $row['wait_time'];
    $output = "Resturant Name: $restaurant_name <br /> Cusine: $cusine <br /> Average Wait Time: $wait_time";
    echo "<div class=\"box\">$output</div>";
endwhile;
?>

这样您就不必使用数组来显示结果。

<header>
    <h2>Here Are Some Places You'd Like To Eat</h2>
</header>

<div class="box">
<?php
  while ($row = mysqli_fetch_array($result)) {
    $row = mysqli_fetch_array($result); 
    echo 'Restaurant name: '.$row['restaurant_name'];
    echo 'Cusine: '.$row['cusine'];
    // ...and so on
  }
?>
</div>

你可以让循环在你的div中使用表格生成HTML。 我不确定你的box类的CSS是什么样的,但这肯定会让你在打印出所有结果时看起来更好。

<header>
  <h2>Here Are Some Places You'd Like To Eat</h2>
</header>
    <div class="box">
      <table>
        <tr>
          <td>Restaurant</td>
          <td>Cusine</td>
          <td>Wait Time</td>
        </tr>
while ($row = mysqli_fetch_array($result)) 
      {
        $restaurant_name = $row['restaurant_name'];
        $cusine = $row['cusine'];
        $wait_time = $row['wait_time'];

        echo "<tr><td>". $restaurant_name . "</td><td>" . $cusine . "</td><td>" . $wait_time . "</td></tr>"; 
      }
     </table>
   </div>

你在每个循环中覆盖你的$ output变量,然后尝试稍后回显$ output; 它只包含上次迭代的数据。

相反,将$ output作为包含数据的数组,然后将其循环以显示:

$output=array();
while ($row = mysqli_fetch_array($result)) :
    $output[]=$row;
endwhile

然后你可以遍历$ output数组来为每个餐厅构建一个输出:

foreach($output as $value):
    $returnDetails='<div class="box">';
    $returnDetails.='Resturant Name: '.$output['restaurant_name'].'<br />';
    // etc. for all details
    $returnDetails.='</div>';
    echo $returnDetails; 
endforeach;

增加了这种方式的好处:如果您想访问循环上下文之外的单行,则可以访问$ output数组

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM