是否可以在同一行的HTML表的多个列中显示单个SQL列?
在此示例中,MySQL中的表具有一列(Col1)。我想将这些数据显示在单个ROW中,但要一列显示在三列中,所以我想将这些数据显示在三列下的三列中以显示最终结果,有没有办法做到这一点?
这是我的代码:
<?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>";
?>
答案 0 :(得分:1)
那里:
<?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>";
?>
答案 1 :(得分:0)
根据评论进行编辑: 将表和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>";
?>