如何使用php外键生成表
我有一个关于PHP查询的问题。 我有两张桌子。如何使用php外键生成表,php,mysql,foreign-keys,Php,Mysql,Foreign Keys,我有一个关于PHP查询的问题。 我有两张桌子。 第一个表格: |id_table1 | first_name | last_name | |----------|------------|-----------| | 1 | John | Doe | | 2 | Doe | John | 第二张表: |id_table2 | hobby | age | id_table1| |----------|--------|
第一个表格:
|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
$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>";
}
}
}
在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>";
}
}
?>
只需保存ftable的id号,然后在第二个表的“for”循环中进行测试,如下所示:
| John Doe | | Doe John |
|----------------| |--------|------|
| Hobby | Age | | Hobby | Age |
|----------|-----| |--------|------|
| football | 17 | |swimming| 19 |
|basketball| 18 |
<?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>";
}
}
}
您的代码看起来怎么样?到目前为止你试过什么?尽量让你的问题更清楚-你有两个mysql表,你想在php中回显表,对吗?