我有这个小代码可以显示200行,并且我想给每行一个数字,即每张选票的编号。
我该怎么做?
这就是我的想法,但它不起作用。
$sql = 'SELECT * FROM table LIMIT 200;
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
$row = 1;
echo $row++;
echo $row['fullname'];
echo '<br>';
}
输出使所有行输出为1。
编辑: 好的,所以有些答案可以解决问题,但是对分页不起作用。它从第2、3、4、5页上的1开始计数。...这是代码。
<?php
$sql = "SELECT * FROM table";
$result = mysqli_query($conn, $sql);
$result_per_page = 20;
$no_of_result = mysqli_num_rows($result);
$no_of_page = ceil($no_of_result/$result_per_page);
if(!isset($_GET['page'])){
$page = 1;
}else{
$page = $_GET['page'];
}
$page_first = ($page-1)*$result_per_page;
$sql = 'SELECT * FROM table LIMIT ' . $page_first . ',' . $result_per_page;
$result = mysqli_query($conn, $sql);
$num = 1;
while($row = mysqli_fetch_assoc($result)) {
echo $num++;
echo $row['fullname'];
echo '<br>';
}
for($page=1;$page<=$no_of_page;$page++){
echo '<a href="/?page='.$page.'">'.$page.'</a>';
echo ' ';
}
?>
答案 0 :(得分:1)
尝试逐行阅读代码,看看它能做什么。
while($row = mysqli_fetch_assoc($result)) { # > Set variable $row to the next result set or exit when there are none.
$row = 1; # Set variable $row to value 1.
echo $row++; # Increment variable $row to + 1.
echo $row['fullname']; # Row is now an integer, not an array. (You did that 2 statements ago)
echo '<br>'; #
} // end of loop, start again --------------|
解决方案是:
$id = 1;
while($row = mysqli_fetch_assoc($result)) {
echo $id++;
echo $row['fullname'];
echo '<br>';
}
对于页面,您正在覆盖先前的值:
for($s=$page;$s<=$no_of_page;$s++){
echo '<a href="/?page='.$s.'">'.$s.'</a>';
echo ' ';
}