答案 0 :(得分:1)
使用php
以降序显示自定义索引$sql ="SELECT * FROM tbl_purchases ORDER BY id DESC";
if ($result = $link->query($sql)) {
$index = mysqli_num_rows($result);
echo "<table border='1'>";
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>".
"<td>{$index}</td/>".
"<td>{$row['id']}</td/>".
"<td>{$row['name']}</td>".
"</tr>";
$index--;
}
echo "</table>";
}
升序索引
$sql ="SELECT * FROM tbl_purchases ORDER BY id DESC";
if ($result = $link->query($sql)) {
$index = 1;
echo "<table border='1'>";
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>".
"<td>{$index}</td/>".
"<td>{$row['id']}</td/>".
"<td>{$row['name']}</td>".
"</tr>";
$index++;
}
echo "</table>";
}
==================
重置DB中的自动增量列(从1开始重新启动)
对于MYISAM
ALTER TABLE tbl_purchases AUTO_INCREMENT = 1;
对于INNO DB
SET @num := 0;
UPDATE tbl_purchases SET id = @num := (@num+1);
ALTER TABLE tbl_purchases AUTO_INCREMENT =1;
答案 1 :(得分:1)
通常,当您从DB获取时,通常处于自动递增状态的ID列不可靠,因此在获取时,您应该运行自己的自动增量。即。
<?php foreach($rows as $index => $row): ?>
<table>
<td><?php echo $index + 1 ?></td>
答案 2 :(得分:1)
当你使用while循环时,你必须在开始循环之前创建一个变量并在循环中将它递增1并将其用作行号:)
$sql ="SELECT * FROM tbl_purchases ORDER BY id DESC";
if ($result = $link->query($sql)) {
echo "<table border='1'>";
$line_counter=mysqli_num_rows($result);
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>".
"<td>{$line_counter}</td/>".
"<td>{$row['id']}</td/>".
"<td>{$row['name']}</td>".
"</tr>";
$line_counter--;
}
echo "</table>";
}