Home >Database >Mysql Tutorial >How to Paginate MySQL Queries with PHP to Display 10 Results Per Page?
PHP & MySQL Pagination
Pagination is crucial when working with large data sets as it allows the user to load only a portion of the relevant data , thereby reducing server load and improving application response speed. This Q&A will guide you on how to use paginated queries with PHP and MySQL.
Question:
How to paginate a MySQL query to display 10 results per page?
Answer:
<?php // 数据库连接代码在此处省略 $perPage = 10; $page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1; $startAt = $perPage * ($page - 1); $query = "SELECT COUNT(*) as total FROM redirect WHERE user_id = '".$_SESSION['user_id']."'"; $r = mysql_fetch_assoc(mysql_query($query)); $totalPages = ceil($r['total'] / $perPage); $links = ""; for ($i = 1; $i <= $totalPages; $i++) { $links .= ($i != $page) ? "<a href='index.php?page=$i'>Page $i</a> " : "$page "; } $query = "SELECT * FROM 'redirect' WHERE 'user_id'= \''.$_SESSION['user_id'].' \' ORDER BY 'timestamp' LIMIT $startAt, $perPage"; $r = mysql_query($query); // 在此处显示结果 echo $links; // 显示其他页面的链接
Explanation:
The above is the detailed content of How to Paginate MySQL Queries with PHP to Display 10 Results Per Page?. For more information, please follow other related articles on the PHP Chinese website!