![](/img/trans.png)
[英]Display a single SQL columns into multiple columns of an HTML table using PHP
[英]Combine multiple SQL columns into a single column of an HTML table using PHP
是否可以將來自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 |
| - - - - - - - - - - - - |
您的HTML有效,但不正確。 這可能是結果表的結構。
創建一個新數組,在其中存儲col2
值,以在所有col1
值之后顯示。 完成col1
值循環后,再次顯示第二個col2
值。
$col2 = array();
echo "<table>";
while ($row = mysqli_fetch_array($sql_query)) {
$col1 = $row['col1'];
$col2[] = $row['col2'];
echo "<tr>";
echo "<td> $col1 </td>";
echo "</tr>";
}
for($i = 0; $ < count($col2); $i++){
echo "<tr>";
echo "<td> $col2[$i] </td>";
echo "</tr>";
}
echo "</table>";
不需要有兩個循環。 可以在單循環中完成。 用不同的變量分隔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>";
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.