php - 表头从 php 中的 for 循环重复

标签 php mysql

我正在尝试从数据库创建排行榜。我将数据打印在列表中。当我尝试将此数据放入 html 表中时,标题在每次数据输入后重复出现。这是 for 循环导致的,但我不知道如何只打印一次标题,然后将数据插入每一行。任何帮助将不胜感激。代码和结果的屏幕截图如下。 提前谢谢你。

    <?php
require_once 'header.php';
    // Send variables for the MySQL database class.
    $database = mysql_connect('localhost', 'root', 'password') or die('Could not connect: ' . mysql_error());
    mysql_select_db('robinsnest') or die('Could not select database');

    $query = "SELECT * FROM `members` ORDER by `quiz_score` DESC LIMIT 10";
    $result = mysql_query($query) or die('Query failed: ' . mysql_error());

    $num_results = mysql_num_rows($result);  

    for($i = 1; $i <= $num_results; $i++)
    {
         $row = mysql_fetch_array($result);
         echo "<table>
  <tr>
    <th>Position</th>
    <th>User Name</th>      
    <th>Score</th>
  </tr>
  <tr>
    <td>".$i."</td>
    <td>".$row['user']."</td>       
    <td>".$row['quiz_score']."</td>
  </tr>

</table>";
    }
    echo '<footer>
                <p class="pull-right"><a href="#">Back to top</a></p>
                <p>&copy; 2014 Company, Inc. &middot; <a href="#">Privacy</a> &middot; <a href="#">Terms</a></p>
            </footer>';
?>

结果是“每次循环用户名和分数后都会重复位置、用户名和分数标题”

最佳答案

从循环中删除 header 。

这样做:

<?php
require_once 'header.php';
    // Send variables for the MySQL database class.
    $database = mysql_connect('localhost', 'root', 'password') or die('Could not connect: ' . mysql_error());
    mysql_select_db('robinsnest') or die('Could not select database');

    $query = "SELECT * FROM `members` ORDER by `quiz_score` DESC LIMIT 10";
    $result = mysql_query($query) or die('Query failed: ' . mysql_error());

    $num_results = mysql_num_rows($result);  

    echo "<table>
          <tr>
          <th>Position</th>
          <th>User Name</th>      
           <th>Score</th>
           </tr>";

    for($i = 1; $i <= $num_results; $i++)
    {
         $row = mysql_fetch_array($result);

         echo "<tr>
              <td>".$i."</td>
              <td>".$row['user']."</td>       
              <td>".$row['quiz_score']."</td>
              </tr>";
    }

    echo "</table>";

    echo '<footer>
                <p class="pull-right"><a href="#">Back to top</a></p>
                <p>&copy; 2014 Company, Inc. &middot; <a href="#">Privacy</a> &middot; <a href="#">Terms</a></p>
            </footer>';
?>

让我知道更多帮助!!

关于php - 表头从 php 中的 for 循环重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29209808/

相关文章:

php - Mysql,复杂的Where子句会减慢查询速度

php - 如何在运行 PHPUnit 的 NetBeans 上修复 "unrecognized option --run"

php - 2.2+版本的moodle开发类(class)

php - 在表和链接表上搜索全文

php - 检查用户名是否存在sql和php中的代码

Mysql 计算具有特定属性的行

使用 mysql_query 函数和安全性的 PHP 参数化查询?

PHP如何限制并行下载?

MySQL - 如何根据单列查找重复行?

php - 在 Laravel 中清理用户输入