Anil Shahi
Anil Shahi

Reputation: 15

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>

Upvotes: 1

Views: 3244

Answers (3)

MH2K9
MH2K9

Reputation: 12039

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>

Upvotes: 2

Asher
Asher

Reputation: 577

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.

Upvotes: 0

Okan Kocyigit
Okan Kocyigit

Reputation: 13421

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>

Upvotes: 0

Related Questions