使用 MySQLi 进行 PHP 分页

PHP Pagination with MySQLi(使用 MySQLi 进行 PHP 分页)
本文介绍了使用 MySQLi 进行 PHP 分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在构建自己的 CMS.我有一个管理系统,我可以用它在数据库中插入帖子,显示帖子不是问题,但我不知道如何进行分页.

I'm building my own CMS. I have an administration system made and I can insert posts in the database with it, showing posts isn't a problem, but I have no idea on how to do the pagination.

这是我的查询:

SELECT * FROM `posts` WHERE `status` != 'draft'

推荐答案

构建您的查询以具有 LIMIT

结束SQL结果;

SELECT * FROM posts WHERE status != 'draft' ORDER BY id ASC LIMIT <<offset>>, <<amount>>

例如;

SELECT * FROM posts WHERE status != 'draft' ORDER BY id ASC LIMIT 0, 10 #Fetch first 10
SELECT * FROM posts WHERE status != 'draft' ORDER BY id ASC LIMIT 10, 10 #Fetch next 10

阅读LIMIT

您将需要 ORDER BY 您的主键,因为在没有 ORDER BY 子句的情况下,依赖 MySQL 给出的顺序在分页方面并不安全"(因为你可能会得到重复的行(在不同的页面上))

You will need to ORDER BY your primary key, as it's not "safe" to rely on the order MySQL gives without the ORDER BY clause, in terms of pagination (as you may get duplicate rows (on different pages))

这样的东西就足够了

$intTotalPerPage = 10;
$intPage = isset($_GET['page']) && ctype_digit($_GET['page']) ? (int) $_GET['page'] : 0;

$strSqlQuery = "SELECT * FROM posts WHERE status != ? ORDER BY `id` ASC LIMIT ?, ?";
$strStatus = 'draft';
$intStart = ($intPage * $intTotalPerPage);
$intLimit = $intTotalPerPage;
$objDbLink = mysqli_connect("...");
$objGetResults = mysqli_prepare($objDbLink, $strSqlQuery);
mysqli_stmt_bind_param($objGetResults, 'sii',  $strStatus, $intStart, $intLimit);
//Execute query and fetch
//Display results

$objTotalRows = mysqli_query("SELECT COUNT(id) AS total FROM posts WHERE status != 'draft'");
$arrTotalRows = mysqli_fetch_assoc($objTotalRows);

$intTotalPages = ceil($arrTotalRows['total'] / $intTotalPerPage);

for ($i = 0; $i <= $intTotalPages; $i++) {
    echo "<a href='?page=" . $i . "'>[" . $i . "]</a>&bsp;";
}

正如评论中所建议的,使用准备语句是一种很好的做法,通过 绑定参数

As suggested in the comments it's good practice to use prepare statements, by binding parameters

这篇关于使用 MySQLi 进行 PHP 分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)