首页 > 数据库 > mysql教程 > 如何用PHP实现简单的数据库分页?

如何用PHP实现简单的数据库分页?

Barbara Streisand
发布: 2025-01-21 19:07:10
原创
241 人浏览过
<code class="language-php"><?php
// Database connection (replace with your credentials)
$host = 'localhost';
$dbname = 'your_database';
$user = 'your_user';
$password = 'your_password';

try {
    $dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}


// Get total number of records
$stmt = $dbh->query('SELECT COUNT(*) FROM your_table');
$totalRecords = $stmt->fetchColumn();


// Pagination settings
$recordsPerPage = 20;
$totalPages = ceil($totalRecords / $recordsPerPage);
$currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$currentPage = max(1, min($currentPage, $totalPages)); // Ensure page number is within valid range

$offset = ($currentPage - 1) * $recordsPerPage;


// Fetch data for current page
$stmt = $dbh->prepare("SELECT * FROM your_table LIMIT :limit OFFSET :offset");
$stmt->bindParam(':limit', $recordsPerPage, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);


// Display data
echo "<h2>Data (Page " . $currentPage . " of " . $totalPages . ")</h2>";
if ($data) {
    echo "<ul>";
    foreach ($data as $row) {
        echo "<li>" . implode(", ", $row) . "</li>"; // Adjust as needed for your table structure
    }
    echo "</ul>";
} else {
    echo "<p>No data found for this page.</p>";
}



// Display pagination links
echo "<div class='pagination'>";
for ($i = 1; $i <= $totalPages; $i++) {
    $activeClass = ($i == $currentPage) ? 'active' : '';
    echo "<a href='?page=" . $i . "' class='" . $activeClass . "'>" . $i . "</a>";
}
echo "</div>";


?>

<!DOCTYPE html>
<html>
<head>
<title>Simple Pagination</title>
<style>
.pagination a {
    display: inline-block;
    padding: 8px 12px;
    margin: 0 4px;
    text-decoration: none;
    border: 1px solid #ccc;
}

.pagination a.active {
    background-color: #4CAF50;
    color: white;
}
</style>
</head>
<body>
</body>
</html>
</code>
登录后复制

How to Implement Simple Database Pagination in PHP?

这个改进的示例包括:

  • 错误处理: try-catch 块处理潜在的数据库连接错误。
  • 准备语句: 使用准备语句来防止 SQL 注入漏洞。 这对于安全至关重要。
  • 输入验证:虽然原始示例使用filter_input,但它缺乏全面​​的验证。 此版本确保页码为正整数且在有效范围内。
  • 更清晰的数据显示:数据以更用户友好的格式(无序列表)显示。 您需要调整 implode 部分以匹配数据库表的列名称。
  • 完整的 HTML: 提供完整的 HTML 结构以实现更好的渲染。
  • CSS 样式: 包含基本 CSS,用于设置分页链接的样式。
  • 占位符值: 请记住将 "your_database""your_user""your_password""your_table" 替换为您的实际数据库凭据和表名称。

请记住在运行此代码之前创建必要的数据库和表。 这个增强的示例为 PHP 分页提供了更强大、更安全的解决方案。

以上是如何用PHP实现简单的数据库分页?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板