gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:01:01 24 4
gpt4 key购买 nike

我正在尝试从数据库创建排行榜。我将数据打印在列表中。当我尝试将此数据放入 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com