Home > Article > Backend Development > How to implement pagination for a MySQL query in PHP?
Pagination in PHP Using MySQL Queries
Pagination allows breaking down large datasets into smaller, manageable pages, making it convenient for users to navigate and access data. This example focuses on implementing pagination for a MySQL query in a PHP script.
To paginate 10 results per page, you can utilize the following code as a starting point:
<code class="php"><?php // Establish MySQL connection $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 "; } $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 results as desired echo $links; // Display links to other pages</code>
This code calculates the total number of pages, generates page links, and returns only the desired results for the current page. You can then display these results in your web page.
The above is the detailed content of How to implement pagination for a MySQL query in PHP?. For more information, please follow other related articles on the PHP Chinese website!