[英]How to echo data into 3 columns in a table in php?
我的代碼僅對2行的6個數據起作用,因為我按asc和desc限制3對其進行了排序,但是我想在數據庫中准確地在3列n行中回顯所有數據。 這是我的代碼:
<table class="table table-striped mt30">
<tbody>
<tr>
<?php
$sql = "select * from services order by id desc limit 3";
$result = mysql_query ($sql);
while ($row = mysql_fetch_array($result)) { ?>
<td><?php echo $row['servies']?></td>
<?php }?>
</tr>
<tr>
<?php
$sql = "select * from services order by id asc limit 3";
$result = mysql_query ($sql);
while ($row = mysql_fetch_array($result)) { ?>
<td> <?php echo $row['servies']?></td>
<?php }?>
</tr>
</tbody>
</table>
取消limit
。 用戶order asc
或desc
。 在while循環中,為print <tr>
和</tr>
保留一個標志。 像這樣...
<?php
$sql = "select * from services order by id asc";
$result = mysql_query ($sql);
?>
<table class="table table-striped mt30">
<tbody>
<?php
$i = 0; $trEnd = 0;
while ($row = mysql_fetch_array($result)){
if($i == 0){
echo '<tr>';
}
echo '<td>'.$row['servies'].'</td>';
if($i == 2){
$i = 0; $trEnd = 1;
}else{
$trEnd = 0; $i++;
}
if($trEnd == 1) {
echo '</tr>';
}
}
if($trEnd == 0) echo '</tr>';
?>
</tbody>
</table>
您應該在每三條記錄打印后放置<tr>
標記,
<table class="table table-striped mt30">
<tbody>
<tr>
$result = mysql_query ("select * from services order by id desc");
$i = 0;
while ($row = mysql_fetch_array($result))
{
if($i % 3 == 0) {
echo "<tr>";
} ?>
<td><?php echo $row['servies']?></td>
if($i % 3 == 0) {
echo "</tr>"
}
$i++;
} ?>
</tr>
</tbody>
</table>
您必須刪除limit 3
,因為您要n行,而limit 3
將獲得3行。 如果您只想顯示數據庫中的3列,請選擇這3列,例如: SELECT col-1, col2, col3
,或者全選並使用PHP顯示您想要的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.