简体   繁体   中英

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. 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 . User order asc or desc . In while loop keep a flag for print <tr> and </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,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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