简体   繁体   English

如何将数据回显到php表中的3列中?

[英]How to echo data into 3 columns in a table in php?

My code only worked for 6 datas for 2 rows since I ordered it by asc and desc limit 3, but I want to echo all the data from database in exactly 3 columns and n rows. 我的代码仅对2行的6个数据起作用,因为我按asc和desc限制3对其进行了排序,但是我想在数据库中准确地在3列n行中回显所有数据。 Here is my code: 这是我的代码:

<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>

Remove limit . 取消limit User order asc or desc . 用户order ascdesc In while loop keep a flag for print <tr> and </tr> . 在while循环中,为print <tr></tr>保留一个标志。 Just like this... 像这样...

<?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>

You should put <tr> tag after print every three records, 您应该在每三条记录打印后放置<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>

You must remove limit 3 , because you want n row, and limit 3 will get you 3 rows. 您必须删除limit 3 ,因为您要n行,而limit 3将获得3行。 If you want to display only 3 columns from DB, select those 3 columns like: SELECT col-1, col2, col3 , or select all and display what you want using PHP. 如果您只想显示数据库中的3列,请选择这3列,例如: SELECT col-1, col2, col3 ,或者全选并使用PHP显示您想要的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM