我已经设法使用 PDO 通过 sqlite 数据库进行分页,但是对于数据库来说是新手,我想知道是否有更好或更有效的方法来做到这一点?这是代码:
<?php
try
{
$db = new PDO('sqlite:comments.s3db');
$per_page = '3';
$result = $db->query("SELECT id FROM com ");
$rows = $result ->fetchAll();
$total_records = count($rows);
$pages = ceil($total_records / $per_page);
$page = (isset ($_GET['page'])) ? (int) $_GET['page'] : 1 ;
$start = ($page - 1) * $per_page;
$query = $db->query("SELECT * FROM com LIMIT $start , $per_page");
while($row = $query->fetch(PDO::FETCH_ASSOC)){
echo '<br>' . $row['id'] . '<br>' . $row['name'] . '<br>' . $row['email'] . '<br>';
} ?>
<br><br>
<?php
if ($pages >= 1 && $page <= $pages){
//if ($page>1 && $page <= $pages){$previous=($page -1); echo '<a href="?page=' .$previous. '">Previous</a>';}
for($x=1; $x<=$pages; $x++){ echo ($x == $page) ? ' <strong><a href="?page='.$x.'">'.$x.'</a></strong> ' : ' <a href="?page='.$x.'">'.$x.'</a> ';}
//if ($page>1 && $page <= $pages){ $next=($page+1) ; echo '<a href="?page=' .$next. '">Next</a>';}
}
####################### Close Database #######################
$db = NULL;
}
catch(PDOException $e)
{
print 'Exception : '.$e->getMessage();
}
?>