从sql回显到表

时间:2015-02-09 01:31:07

标签: php sql select html-table echo

我需要从mysql中选择一些数据并将它们回显到表中, 我有20个条目,我想将它们回显到5by4表中,我可以像这样选择它们:

<?php
         $sql = "SELECT player FROM `prize` WHERE inviter='$player'";
         $result = $conn->query($sql);
         if ($result->num_rows > 0) {

         ?>
         <table style="width: 100%;border:1px">
         <tr> <td class="auto-style3">
<?php

     while($row = $result->fetch_assoc()) {
?>

                    <?php echo "<br>". $row["player"].""; ?>
<?php
}} 

         ?>


   </td>  </tr>   </table>

它给我这样的东西:

enter image description here

但我希望这样:

enter image description here

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

尝试这样,使用$ count来计算数组中的项目。并且在回显了5个项目之后,您将<tr>置于新行回显

<?php
  $count=0;
  echo "<table>";
  while($row = $result->fetch_assoc()) {
    if($count==0) {
      echo "<tr>";
    }
    $count++;
    echo "<td>".$row["player"]."</td>";
    if($count==5) {
      echo "</tr>";
      $count=0;
    }
  }   
  echo "</table>";
?>

答案 1 :(得分:0)

我更改了您的代码以添加计数器并每隔五条记录关闭一次标记,结果就是:

&#13;
&#13;
<?php
         $sql = "SELECT player FROM `prize` WHERE inviter='$player'";
		 $result = $conn->query($sql);
		 if ($result->num_rows > 0) {
		 
		 ?>
		 <table style="width: 100%;border:1px">
		 <tr>
           <?php

                $counter=0;
                while($row = $result->fetch_assoc()) {
                if($counter == 4){
                   echo '</tr><tr>';
                   $counter=0;
                }
            ?>

              <td><?php echo $row["player"].""; ?></td>

            <?php

              $counter++;

            }} 

           ?> 
       
        
   </tr>   </table>
&#13;
&#13;
&#13;