【问题标题】:Auto Increase in PHP for HTML TableHTML表格的PHP自动增加
【发布时间】:2013-10-01 02:02:30
【问题描述】:

我正在尝试制作结果表。

这是目前表格的样子:

<?php
        $row = mysql_query("SELECT * FROM table ORDER BY Votes DESC LIMIT 5");
        while($sql = mysql_fetch_assoc($row)){
        ?>
        <tr>
            <td width="5%" align="center"><?php $rank=1; echo $rank;?></td>
            <td width="15%" align="center"><img src="/pictures/<?php echo $sql['Picture']; ?>.png" height="50%"></td>
            <td width="7%" align="center"><?php echo $sql['Votes']; ?></td>
        </tr>
              <?php } ?>

这是目前为止的代码。我正在努力做到这一点,所以排名会自动增加。顺便说一句,排名不是来自数据库,但我只是希望它从 1 开始然后增加。请帮帮我。

【问题讨论】:

    标签: php html html-table


    【解决方案1】:
    <?php
        $row = mysql_query("SELECT * FROM table ORDER BY Votes DESC LIMIT 5");
    
        $rank = 0; // default rank
        while($sql = mysql_fetch_assoc($row))
        {
            $rank += 1; // increase
        ?>
            <tr>
                <td width="5%" align="center"><?php echo $rank;?></td>
                <td width="15%" align="center"><img src="/pictures/<?php echo $sql['Picture']; ?>.png" height="50%"></td>
                <td width="7%" align="center"><?php echo $sql['Votes']; ?></td>
            </tr>
    <?php } ?>
    

    【讨论】:

    • 非常感谢。没想到会这么简单。
    【解决方案2】:

    你的问题是 $rank 变量是在 while 循环中声明的

    <td width="5%" align="center"><?php $rank=1; echo $rank; //this line ?></td>
    

    所以你需要把它移出循环,因为当循环继续时它会再次设置为1(这就是为什么总是显示1)

    要解决问题,您应该这样做

    <?php
        $row = mysql_query("SELECT * FROM table ORDER BY Votes DESC LIMIT 5");
        $rank = 1; // declare rank here
        while($sql = mysql_fetch_assoc($row)){
        ?>
        <tr>
            <td width="5%" align="center"><?php echo $rank++; // increase rank by 1 each times the loop run ?></td>
            <td width="15%" align="center"><img src="/pictures/<?php echo $sql['Picture']; ?>.png" height="50%"></td>
            <td width="7%" align="center"><?php echo $sql['Votes']; ?></td>
        </tr>
    <?php } ?>
    

    希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 2016-04-26
      • 2017-03-01
      • 2018-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-27
      • 2018-12-06
      相关资源
      最近更新 更多