是否可以将 MySQL 表中多列的数据合并到 HTML 表中的单个列中,其中每条记录都将成为 HTML 表中的新行?
在此示例中,MySQL 中的表有两列(Col1、Col2)。 Col1 中的数据显示在 HTML 表格的第一列中。 MySQL 中 Col2 的数据显示在 HTML 表格的第二列中。换句话说,HTML 表格与 MySQL 表格的布局相匹配。
<?php
$con = new mysqli('domain', 'username', 'password', 'database');
$sql = "select * from table1";
$sql_query = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($sql_query)) {
$col1 = $row['col1'];
$col2 = $row['col2'];
echo "<table>";
echo "<tr>";
echo "<td> $col1 </td>";
echo "<td> $col2 </td>";
echo "</tr>";
echo "</table>";
}
?>
MySQL 表:
| - - - - | - - - - - - - |
| Col1 | Col2 |
| - - - - | - - - - - - - |
| Blue | Car |
| Green | Truck |
| Yellow | Van |
| - - - - | - - - - - - - |
HTML 表格:
| - - - - | - - - - - - - |
| Column1 | Column2 |
| - - - - | - - - - - - - |
| Blue | Car |
| Green | Truck |
| Yellow | Van |
| - - - - | - - - - - - - |
如果将 $col1 和 $col2 放入单个 TD 标记内,则 $col1 和 $col2 都会显示在 HTML 表格的 Col1 中。但是,$col1 和 $col2 都显示在同一单元格中。
<?php
$con = new mysqli('domain', 'username', 'password', 'database');
$sql = "select * from table1";
$sql_query = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($sql_query)) {
$col1 = $row['col1'];
$col2 = $row['col2'];
echo "<table>";
echo "<tr>";
echo "<td> $col1 $col2 </td>";
echo "</tr>";
echo "</table>";
}
?>
HTML 表格:
| - - - - - - - - - - - - |
| Column1 |
| - - - - - - - - - - - - |
| Blue Car |
| Green Truck |
| Yellow Van |
| - - - - - - - - - - - - |
是否可以在 HTML 表格的 Column1 中回显 $Col1 和 $Col2,并使每条记录位于 HTML 表格中自己的行中?
| - - - - - - - - - - - - |
| Column1 |
| - - - - - - - - - - - - |
| Blue |
| Green |
| Yellow |
| Car |
| Truck |
| Van |
| - - - - - - - - - - - - |
最佳答案
不需要有两个循环。它可以在单个循环中完成。将不同变量中的 col1 和 col2 值分开。并在最后打印它。
<?php
$con = new mysqli('domain', 'username', 'password', 'database');
$sql = "select * from table1";
$sql_query = mysqli_query($con, $sql);
$str = "<table>";
$str_col2 = "";
while ($row = mysqli_fetch_array($sql_query)) {
$col1 = $row['col1'];
$col2 = $row['col2'];
$str .= "<tr><td> $col1 </td></tr>";
$str_col2 .= "<tr><td> $col2 </td></tr>";
}
echo $str . $str_col2 . "</table>";
?>
关于php - 使用 PHP 将多个 SQL 列合并到 HTML 表的单个列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37084296/