如何显示while循环计数器变量

时间:2018-09-26 06:03:42

标签: php

在下面的代码中,从表头“ Sr.No.”的第一列中的mysql表中获取数据。我想在表数据中显示循环计数器变量$ no。 任何人都可以说出正确的语法。

<table id = "result" class="data-table">
        <caption class="title"></caption>
        <thead>
            <tr>    

                <th>Sr.No.</th>
                <th>Student ID</th>
                <th>Student Name</th>
                <th>Marks Obtained</th>
            </tr>
        </thead>
        <tbody>

        <?php
        $no     = 1;
        $total  = 0;
        while ($row = mysqli_fetch_array($query))
        {
            $stu  = $row['stu_id'] == 0 ? '' : number_format($row['stu_id']);
            echo '<tr>


                    <td>''</td>
                    <td>'.$row['student_id'].'</td>
                    <input type="hidden" name="student_id" value='.$row['student_id'].'>
                    <td>'.$row['student_name'].'</td>
                    <input type="hidden" name="student_name" value='.$row['student_name'].'>
                    <td>'."<div class='search-block clearfix'><input name='obtmarks' placeholder='' type='number'></div>".'</td>

                </tr>';
            $total += $row['stu_id'];

            $no++;


        }?>
        </tbody>

    </table>

2 个答案:

答案 0 :(得分:1)

您可以打印$ no变量值:

<table id = "result" class="data-table">
    <caption class="title"></caption>
    <thead>
        <tr>    

            <th>Sr.No.</th>
            <th>Student ID</th>
            <th>Student Name</th>
            <th>Marks Obtained</th>
        </tr>
    </thead>
    <tbody>

    <?php
    $no     = 1;
    $total  = 0;
    while ($row = mysqli_fetch_array($query))
    {
        $stu  = $row['stu_id'] == 0 ? '' : number_format($row['stu_id']);
        echo '<tr>


                <td>'.$no.'</td>
                <td>'.$row['student_id'].'</td>
                <input type="hidden" name="student_id" value='.$row['student_id'].'>
                <td>'.$row['student_name'].'</td>
                <input type="hidden" name="student_name" value='.$row['student_name'].'>
                <td>'."<div class='search-block clearfix'><input name='obtmarks' placeholder='' type='number'></div>".'</td>

            </tr>';
        $total += $row['stu_id'];

        $no++;


    }?>
    </tbody>

</table>

答案 1 :(得分:1)

@Akhtar,我了解您对PHP领域来说还很陌生。您以前收到的所有答案都是正确的,但是我想通过一些小样式建议为您的问题做些贡献,这些建议将帮助您编写好的代码并亲自发现最终的问题。

更改:

  • 常规变量移至顶部
  • PHP不再打印HTML,而只是打印内容
  • 将所有新变量合并到一个块(Editor\Data\Mono\lib\mono\2.0Editor\Data\MonoBleedingEdge\lib\mono\4.5
  • 注释了未使用的变量(也许您会在将来的开发中使用它)
  • $total元素移至$stu(单元格之间不应有代码)
  • 统一引号(input)和双引号(td),带双引号的HTML,带引号的PHP
  • 用更清晰的语法更改了while括号(您会发现它对于长HTML很有用)

通过这些更改,如果您要使用现代IDE,您将获得更好的建议,并且代码突出显示将为您提供帮助。

新代码:

'