PHP 和 MySQL 分页
Web 应用程序的一个常见任务是以分页格式显示大型数据集,允许用户查看有限的数据集每页的结果数。这可以增强用户体验和性能。
考虑一个 MySQL 查询,该查询从按用户 ID 筛选的“重定向”表中检索所有记录:
SELECT * FROM redirect WHERE user_id = '".$_SESSION['user_id']."' ORDER BY 'timestamp'
对此查询进行分页,以便它每页显示 10 个结果,请按照以下步骤操作:
<?php // Insert your MySQL connection code here // Set the number of results per page $perPage = 10; // Get the current page number from GET request (or default to 1) $page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1; // Calculate the starting record for the specified page $startAt = $perPage * ($page - 1); // Count the total number of records in the table $query = "SELECT COUNT(*) as total FROM redirect WHERE user_id = '".$_SESSION['user_id']."'"; $r = mysql_fetch_assoc(mysql_query($query)); // Calculate the total number of pages $totalPages = ceil($r['total'] / $perPage); // Generate the pagination links $links = ""; for ($i = 1; $i <= $totalPages; $i++) { $links .= ($i != $page ) ? "<a href='index.php?page=$i'>Page $i</a> " : "$page "; } // Execute the paginated query $r = mysql_query($query); $query = "SELECT * FROM `redirect` WHERE `user_id`= '".$_SESSION['user_id']."' ORDER BY 'timestamp' LIMIT $startAt, $perPage"; $r = mysql_query($query); // Display the results using the pagination system echo $links; // Show links to other pages ?>
以上是如何实现大型数据集的PHP和MySQL分页?的详细内容。更多信息请关注PHP中文网其他相关文章!