如何使用php外键制作表

时间:2017-03-04 11:26:14

标签: php mysql foreign-keys

我对PHP查询有疑问。 我有2张桌子。
第一张表:

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

第二张表:

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

我想像这样制作表格:

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

在php中制作该表的语法是什么?可能正在使用foreach,但如何? 感谢。

代码

<?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 个答案:

答案 0 :(得分:0)

只需保存ftable的id号,然后在第二个表的'for'循环中测试它,如下所示:

    <?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>";
           }
       }
    }