[英]How to display while loop counter variable
在下面的代碼中,從mysql表的表頭'Sr.No.'的第一列中獲取數據。 我想在表數據中顯示循環計數器變量$ 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>
您可以打印$ 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>
@Akhtar,我了解您對PHP領域來說還很陌生。 您以前收到的所有答案都是正確的,但是我想用一些小樣式建議為您的問題做些貢獻,這些建議將幫助您編寫好的代碼並親自發現最終的問題。
變化:
$total
和$stu
) input
元素移入td
(單元格之間不應有代碼) '
)和雙引號( "
),帶雙引號的HTML,帶引號的PHP 通過這些更改,如果您要使用現代的IDE,則將有更好的建議,並且代碼突出顯示將為您提供幫助。
新代碼:
<?php
$no = 0;
$total = 0;
?>
<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 while ($row = mysqli_fetch_array($query)): ?>
<?php
$total += $row['stu_id'];
//aren't you using this variable?
//$stu = $row['stu_id'] == 0 ? '' : number_format($row['stu_id']);
?>
<tr>
<td><?php echo ++$no ?></td>
<td><?php echo $row['student_id'] ?></td>
<td><?php echo $row['student_name'] ?></td>
<td>
<input type="hidden" name="student_id" value="<?php echo $row['student_id'] ?>">
<input type="hidden" name="student_name" value="<?php echo $row['student_name'] ?>">
<div class="search-block clearfix">
<input name="obtmarks" placeholder="" type="number">
</div>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.