![](/img/trans.png)
[英]Combine multiple SQL columns into a single column of an HTML table using PHP
[英]Display a single SQL columns into multiple columns of an HTML table using PHP
是否可以将单个 SQL 列显示到同一行中 HTML 表的多列中?
在这个例子中,MySQL 中的一个表有一个列 (Col1)。 我想在单个 ROW 中显示这些数据,但是在一个旁边的 3 列中显示这些数据,所以我想将这些数据显示在 3 列下的 3 列到最终结果中,有没有办法做到这一点?
这是我的代码:
<?php
$con = new mysqli('domain', 'username', 'password', 'database');
$sql = "select * from table1";
$sql_query = mysqli_query($con, $sql);
echo "<table>";
echo "<tr>";
while ($row = mysqli_fetch_array($sql_query)) {
$col1 = $row['col1'];
echo "<td> $col1 </td>";
echo "<td> $col1 </td>";
echo "<td> $col1 </td>"; //The problem here that these data will repeat because we put the same variable in 3 TD and i want my data doesn't repeat.
}
echo "</tr>";
echo "</table>";
?>
那里:
<?php
$con = new mysqli('domain', 'username', 'password', 'database');
$sql = "select * from table1";
$sql_query = mysqli_query($con, $sql);
echo "<table>";
echo "<tr>";
$pos = 0;
$results_per_row = 3; #you can change it to a different value
while($row = mysqli_fetch_array($sql_query)){
$pos++;
$col1 = $row['col1'];
echo "<td> $col1 </td>";
if($pos % $results_per_row == 0)
echo "</tr><tr>";
}
// fill the last row with empty fields, if it has less than
// $results_per_row values, to keep the proper table syntax
while($pos % $results_per_row != 0){
$pos++;
echo "<td></td>";
}
echo "</tr>";
echo "</table>";
?>
根据评论编辑:将 table 和 tr 标签移到循环之外。
<?php
$con = new mysqli('domain', 'username', 'password', 'database');
$sql = "select * from table1";
$sql_query = mysqli_query($con, $sql);
echo "<table><tr>";
while ($row = mysqli_fetch_array($sql_query)) {
$col1 = $row['col1'];
echo "<td> $col1 </td>";
}
echo "</tr></table>";
?>
上一个回复
我不完全确定您在寻找什么,但我认为您担心的是您正在重复多个表并输出一个值?
如果是这样,您应该将表格开头和结尾的标签移到循环之外,然后对于每个单元格,回显该单元格所需的实际值。
<?php
$con = new mysqli('domain', 'username', 'password', 'database');
$sql = "select * from table1";
$sql_query = mysqli_query($con, $sql);
echo "<table>";
echo "<tr><th>Col 1 Header Name</th><th>Col 2 Header Name</th><th>Col 3 Header Name</th></tr>";
while ($row = mysqli_fetch_array($sql_query)) {
echo "<tr>";
echo "<td> $row['col1'] </td>";
echo "<td> $row['col2'] </td>";
echo "<td> $row['col3'] </td>";
echo "</tr>";
}
echo "</table>";
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.