我在数据库中有两个表。

TABLE ROOM具有以下列和数据

id(int)    room_type(varchar)      price(int)
 1           single room              25000
 2           double room              50000

And TABLE ROOM_IMAGE has the following columns and data

id(int)     image(varchar)         room_id(int)
 1            single.jpg                 1
 2            single1.jpg                1
 3            double.jpg                 2

When i use the following PHP code:

    <?php
    $query = "SELECT a.room_type, s.image FROM room as a
            JOIN room_image as s
            ON a.id = s.room_id ";
?>
<?php if ($rooms = $mysqli->query($query)) { ?>

  <?php while ($room = $rooms->fetch_object()) { ?>

    <h4><?php echo $room->type; ?></h4>
    <p><?php echo $room->image; ?></p>

  <?php } ?>

<?php } ?>


我得到以下结果:

        单人房
       single.jpg
    单人房
           single1.jpg
    双人间
           double.jpg


但是我希望我的结果显示如下

        单人房
           single.jpg
           single1.jpg
        双人间
           double.jpg


因此有人可以帮助我编写适当的php语法以产生所需的结果(最好使用join sql语句)

最佳答案

首先根据房间类型在查询中添加ORDER BY子句。这会将每种类型的所有房间排在一起

$query = "SELECT a.room_type, s.image FROM room as a
        JOIN room_image as s
        ON a.id = s.room_id  ORDER BY a.room_type";


然后,仅在以前未显示过的情况下显示类型。使用一个额外的变量来跟踪它。

 <?php
  $lastType="";
  while ($room = $rooms->fetch_object())
    {
      if($lastType!=$room->type)
      {
       echo "<h4>",$room->type,"</h4>";
      }
      echo "<p>",$room->image,"</p>";
      $lastType=$room-type;          // This variable keeps track of room type display
    }
 ?>

关于php - 遍历数据库表数据并以适当的格式显示,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24279211/

10-11 03:56
查看更多