<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>
這個改進的範例包括:
try-catch
區塊處理潛在的資料庫連線錯誤。 filter_input
,但它缺乏全面的驗證。 此版本確保頁碼為正整數且在有效範圍內。 implode
部分以符合資料庫表的列名稱。 "your_database"
、"your_user"
、"your_password"
和 "your_table"
替換為您的實際資料庫憑證和表格名稱。 請記住在運行此程式碼之前建立必要的資料庫和表。 這個增強的範例為 PHP 分頁提供了更強大、更安全的解決方案。
以上是如何用PHP實作簡單的資料庫分頁?的詳細內容。更多資訊請關注PHP中文網其他相關文章!