豌豆Ai站群搜索引擎系统 V.25.10.25 网址:www.wd.chat

🗣 Wd提问: php分页api

🤖 Ai回答:
我来为你提供一个完整的PHP分页API实现方案。

1、数据库连接类

php
<?php
// Database.php
class Database {
private $host = 'localhost';
private $dbname = 'your_database';
private $username = 'your_username';
private $password = 'your_password';
private $pdo;

public function __construct() {
try {
$this-pdo = new PDO(
mysql:host={$this-host};dbname={$this-dbname};charset=utf8,
$this-username,
$this-password,
[
PDO::ATTR_ERRMODE = PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE = PDO::FETCH_ASSOC
]
);
} catch (PDOException $e) {
throw new Exception(数据库连接失败: 、$e-getMessage());
}
}

public function getPDO() {
return $this-pdo;
}
}
?

2、分页类

php
<?php
// Paginator.php
class Paginator {
private $pdo;
private $table;
private $perPage;
private $currentPage;
private $totalRecords;
private $totalPages;
private $offset;

public function __construct($pdo, $table, $perPage = 10) {
$this-pdo = $pdo;
$this-table = $table;
$this-perPage = $perPage;
$this-currentPage = 1;
}

public function setCurrentPage($page) {
$this-currentPage = max(1, (int)$page);
return $this;
}

public function setPerPage($perPage) {
$this-perPage = max(1, min(100, (int)$perPage)); // 限制每页最大100条
return $this;
}

public function getTotalRecords() {
if ($this-totalRecords === null) {
$sql = SELECT COUNT(*) as count FROM {$this-table};
$stmt = $this-pdo-query($sql);
$this-totalRecords = $stmt-fetch()['count'];
}
return $this-totalRecords;
}

public function getTotalPages() {
if ($this-totalPages === null) {
$this-totalPages = ceil($this-getTotalRecords() / $this-perPage);
}
return $this-totalPages;
}

public function getOffset() {
return ($this-currentPage 1) * $this-perPage;
}

public function getData($columns = '*', $conditions = [], $orderBy = '') {
$this-getTotalRecords(); // 确保总记录数已计算

$sql = SELECT {$columns} FROM {$this-table};

// 添加条件
if (!empty($conditions)) {
$whereClause = [];
foreach ($conditions as $key = $value) {
$whereClause[] = {$key} = :{$key};
}
$sql .= WHERE 、implode(' AND ', $whereClause);
}

// 添加排序
if (!empty($orderBy)) {
$sql .= ORDER BY {$orderBy};
}

// 添加分页
$sql .= LIMIT :limit OFFSET :offset;

$stmt = $this-pdo-prepare($sql);

// 绑定条件参数
foreach ($conditions as $key = $value) {
$stmt-bindValue(:{$key}, $value);
}

$stmt-bindValue(':limit', $this-perPage, PDO::PARAM_INT);
$stmt-bindValue(':offset', $this-getOffset(), PDO::PARAM_INT);

$stmt-execute();
return $stmt-fetchAll();
}

public function getPaginationInfo() {
return [
'current_page' = $this-currentPage,
'per_page' = $this-perPage,
'total_records' = $this-getTotalRecords(),
'total_pages' = $this-getTotalPages(),
'has_previous' = $this-currentPage 1,
'has_next' = $this-currentPage < $this-getTotalPages(),
'previous_page' = $this-currentPage 1 ? $this-currentPage 1 : null,
'next_page' = $this-currentPage < $this-getTotalPages() ? $this-currentPage + 1 : null
];
}

public function toArray($data) {
return [
'data' = $data,
'pagination' = $this-getPaginationInfo()
];
}
}
?

3、API接口文件

php
<?php
// api.php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type');

require_once 'Database.php';
require_once 'Paginator.php';

try {
$db = new Database();
$pdo = $db-getPDO();

// 获取请求参数
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 10;
$table = isset($_GET['table']) ? $_GET['table'] : 'users';

// 验证表名(防止SQL注入)
$allowedTables = ['users', 'products', 'posts']; // 允许的表名
if (!in_array($table, $allowedTables)) {
throw new Exception('无效的表名');
}

// 创建分页器
$paginator = new Paginator($pdo, $table, $perPage);
$paginator-setCurrentPage($page);

// 获取数据
$data = $paginator-getData('*', [], 'id DESC');

// 返回结果
echo json_encode($paginator-toArray($data), JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
http_response_code(500);
echo json_encode([
'error' = true,
'message' = $e-getMessage()
], JSON_UNESCAPED_UNICODE);
}
?

4、高级分页API(支持搜索和过滤)

php
<?php
// advanced_api.php
header('Content-Type: application/json; charset=utf-8');

require_once 'Database.php';
require_once 'Paginator.php';

class AdvancedPaginator extends Paginator {
private $searchFields = [];
private $searchKeyword = '';

public function setSearch($fields, $keyword) {
$this-searchFields = $fields;
$this-searchKeyword = $keyword;
return $this;
}

public function getData($columns = '*', $conditions = [], $orderBy = '') {
$this-getTotalRecords(); // 确保总记录数已计算

$sql = SELECT {$columns} FROM {$this-table};

$params = [];

// 添加条件
$whereClause = [];
foreach ($conditions as $key = $value) {
$whereClause[] = {$key} = :{$key};
$params[:{$key}] = $value;
}

// 添加搜索条件
if (!empty($this-searchKeyword) && !empty($this-searchFields)) {
$searchConditions = [];
foreach ($this-searchFields as $field) {
$searchConditions[] = {$field} LIKE :search_keyword;
}
$whereClause[] = '(' 、implode(' OR ', $searchConditions) 、')';
$params[':search_keyword'] = '%' 、$this-searchKeyword 、'%';
}

if (!empty($whereClause)) {
$sql .= WHERE 、implode(' AND ', $whereClause);
}

// 添加排序
if (!empty($orderBy)) {
$sql .= ORDER BY {$orderBy};
}

// 添加分页
$sql .= LIMIT :limit OFFSET :offset;

$stmt = $this-pdo-prepare($sql);

// 绑定所有参数
foreach ($params as $key = $value) {
$stmt-bindValue($key, $value);
}

$stmt-bindValue(':limit', $this-perPage, PDO::PARAM_INT);
$stmt-bindValue(':offset', $this-getOffset(), PDO::PARAM_INT);

$stmt-execute();
return $stmt-fetchAll();
}

public function getTotalRecords() {
if ($this-totalRecords === null) {
$sql = SELECT COUNT(*) as count FROM {$this-table};

$params = [];
$whereClause = [];

// 添加搜索条件到总数查询
if (!empty($this-searchKeyword) && !empty($this-searchFields)) {
$searchConditions = [];
foreach ($this-searchFields as $field) {
$searchConditions[] = {$field} LIKE :search_keyword;
}
$whereClause[] = '(' 、implode(' OR ', $searchConditions) 、')';
$params[':search_keyword'] = '%' 、$this-searchKeyword 、'%';
}

if (!empty($whereClause)) {
$sql .= WHERE 、implode(' AND ', $whereClause);
}

$stmt = $this-pdo-prepare($sql);
foreach ($params as $key = $value) {
$stmt-bindValue($key, $value);
}

$stmt-execute();
$this-totalRecords = $stmt-fetch()['count'];
}
return $this-totalRecords;
}
}

try {
$db = new Database();
$pdo = $db-getPDO();

// 获取请求参数
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 10;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$table = isset($_GET['table']) ? $_GET['table'] : 'users';

// 验证表名
$allowedTables = ['users', 'products', 'posts'];
if (!in_array($table, $allowedTables)) {
throw new Exception('无效的表名');
}

// 创建高级分页器
$paginator = new AdvancedPaginator($pdo, $table, $perPage);
$paginator-setCurrentPage($page);

// 设置搜索
if (!empty($search)) {
$searchFields = [
'users' = ['name', 'email'],
'products' = ['name', 'description'],
'posts' = ['title', 'content']
];
$paginator-setSearch($searchFields[$table], $search);
}

// 获取数据
$data = $paginator-getData('*', [], 'id DESC');

// 返回结果
echo json_encode($paginator-toArray($data), JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
http_response_code(500);
echo json_encode([
'error' = true,
'message' = $e-getMessage()
], JSON_UNESCAPED_UNICODE);
}
?

5、使用示例

基本分页请求

GET /api.php?page=1&per_page=10&table=users

搜索分页请求

GET /advanced_api.php?page=1&per_page=10&table=users&search=john

响应格式
json
{
data: [
{
id: 1,
name: John Doe,
email: john@65.hk,
created_at: 2023-01-01 12:00:00
}
],
pagination: {
current_page: 1,
per_page: 10,
total_records: 100,
total_pages: 10,
has_previous: false,
has_next: true,
previous_page: null,
next_page: 2
}
}

6、前端调用示例

javascript
// JavaScript调用示例
async function fetchUsers(page = 1, perPage = 10, search = '') {
try {
let url = `/advanced_api.php?page=${page}&per_page=${perPage}&table=users`;
if (search) {
url += `&search=${encodeURIComponent(search)}`;
}

const response = await fetch(url);
const result = await response.json();

if (result.error) {
throw new Error(result.message);
}

return result;
} catch (error) {
console.error('获取数据失败:', error);
throw error;
}
}

// 使用示例
fetchUsers(1, 10, 'john')
.then(result = {
console.log('用户数据:', result.data);
console.log('分页信息:', result.pagination);
})
.catch(error = {
console.error('错误:', error);
});

这个PHP分页API提供了以下功能:

1、基本分页:支持页码和每页数量设置
2、搜索功能:支持多字段搜索
3、安全防护:防止SQL注入,限制每页最大记录数
4、标准化响应:统一的JSON响应格式
5、错误处理:完善的异常处理机制
6、跨域支持:支持CORS跨域请求

你可以根据具体需求调整表名、字段和业务逻辑。

Ai作答

📣 商家广告


公司

广告招商

广告招商

广告招商

vps


0

IP地址: 67.159.88.219

搜索次数: 0

提问时间: 2025-11-04 00:51:36

🛒 域名购买
y-u.com.cn
815.red
pfyj.cn
2111.top
mv8.net
62.gs
wd.chat
6.tj.cn
toutian.com.cn
67.gs

❓️ 热门提问
长治网页开发
服务器机柜价格多少
国内哪些云服务器
便宜国内云服务器的
ftp虚拟主机
电梯机房巡查表电子版
公司网页建设公司
西班牙原生vps
服务器 免费试用
eu.org 域名申请
豌豆Ai站群搜索引擎系统

🌐 域名评估
mg.gs
vr.net.cn
uu.hn.cn
vivo.sd.cn
katetoys.com
mqie.cn
zz.gz.cn
q-j.cn
mm.hn.cn
yu8.jl.cn

⛏ 最新挖掘
凯里酸汤鱼
贵阳烤脑花
都匀毛尖茶
花溪牛肉粉
贵阳烤生蚝
贵阳烤豆腐
贵阳纸包鱼
贵阳特色菜

🖌 热门作画

🤝 关于我们:
豌豆Ai 域名 建站 站群 留痕 推广 评估 源码
开发Ai 工具 日记 价格 加盟 广告 流量 留言 联系

🗨 加入群聊
群

🔗 友情链接
google优化公司  网站搜尋器  ai提问

🧰 站长工具
Ai工具  whois查询  搜索

📢 温馨提示:本站所有问答由Ai自动创作,内容仅供参考,若有误差请用“联系”里面信息通知我们人工修改或删除。

👉 技术支持:本站由豌豆Ai提供技术支持,使用的最新版:《豌豆Ai站群搜索引擎系统 V.25.10.25》搭建本站。

上一篇 57798 57799 57800 下一篇