doujiao4705 2017-03-04 11:26
浏览 25
已采纳

如何使用php外键制作表

I have a question about PHP query. I have 2 tables.
First Table:

|id_table1 | first_name | last_name |
|----------|------------|-----------|
|    1     |    John    |    Doe    |
|    2     |    Doe     |    John   |

Second Table:

|id_table2 | hobby  | age | id_table1|
|----------|--------|-----|----------|
|    1     |football| 17  |    1     |
|    2     |swimming| 18  |    2     |

I want to make table like this:

|    John Doe    |       |   Doe John    |
|----------------|       |--------|------|
|   Hobby  | Age |       |  Hobby |  Age | 
|----------|-----|       |--------|------|
| football | 17  |       |swimming|  19  |
|basketball| 18  |

What is the syntax to make that table in php? May be using foreach, but how? Thanks.

The code

<?php
$ftable="select * from ftable";
$stable="select * from stable";
$ftable1= mysqli_query($conn, $ftable);
$stable1= mysqli_query($conn, $stable);
foreach ($ftable as $row) {
 echo "
  <tr>
   <th style='text-align: center' colspan='2'>".$row['first_name']."</th>
  </tr>
  <tr>
   <th>Hobby</th>
   <th>Age</th>
   </tr>";

 foreach ($ftable1 as $row1) {
  echo "
   <tr>
    <td>".$row1['hobby']."</td>
    <td>".$row1['age']."</td>
    <tr>";
 }
}
?>
  • 写回答

1条回答 默认 最新

  • dongliao9018 2017-03-04 13:18
    关注

    Just save the id number of ftable, then test for it in your 'for' loop for the second table, like this:

        <?php
        $ftable="select * from ftable";
        $stable="select * from stable";
        $ftable1= mysqli_query($conn, $ftable);
        $stable1= mysqli_query($conn, $stable);
        foreach ($ftable1 as $row) {
          $id_table1 = $row["id_table1"]; 
          echo "<tr><th style='text-align: center' colspan='2'>"
             .$row['first_name']."</th></tr>"
                 ."<tr><th>Hobby</th>"
                 ."<th>Age</th></tr>";
    
           foreach ($stable1 as $row1) {
               if ($row1["id_table1"] == $id_table1) {
                  echo "<tr><td>$row1['hobby']</td><td>$row1['age']</td></tr>";
               }
           }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址