如何获取表的最后一个 ID


How to get the last ID of the table

我正在实现一个代码,该代码获取当前投资组合的当前ID,并制作"上一个"和"下一个"按钮来浏览下一个和上一个图像。ID 像 1、3、5、7 等,不是连续的。我想知道如何在到达表中的 las ID 时禁用"下一步"链接。

<?php
foreach($connection->query('SELECT * FROM table WHERE id = (select min(id) from table where id > '.$myid.')') as $row) {
}
foreach($connection->query('SELECT * FROM table WHERE id = (select max(id) from table where id < '.$myid.')') as $row1) {
}
        echo "<a class='anterior' href='http://miweb.com/proyecto/id/".$row1['id']."'>Previous</a>";
?>
<a class="siguiente" href="http://miweb.com/proyecto/id/<?php echo $row['id']; ?>">Next</a>

这种方法看起来像是非常原始的紧缩。您可以使用 LIMIT 进行分页的良好做法。例如,对于 MySQL:

$currentPage = 10;
$pageSize = 100;
// Display current page data
$sql = "SELECT * FROM `table` LIMIT :offset :pagesize";
$stmt = $connection->prepare($sql);
$stmt->execute([
    ':offset' => $pageSize * $currentPage,
    ':pagesize' => $pageSize,
]);
$data = $stmt->fetchAll();
print_r($data);
// Display Next button
$sql = "SELECT count(*) FROM `table`";
$stmt = $connection->prepare($sql);
$stmt->execute();
$count = $stmt->fetchColumn();
if ($pageSize * ($currentPage + 1) < $count) {
    echo '<a href="...' . ($currentPage + 1) . '...">Next</a>';
}