How can PHP developers avoid common pitfalls when implementing pagination with multiple queries?
When implementing pagination with multiple queries in PHP, developers can avoid common pitfalls by using a single query to fetch the total number of rows and another query to fetch the paginated results. This approach reduces the number of database calls and improves performance. Additionally, developers should properly sanitize user input to prevent SQL injection attacks.
// Calculate total number of rows
$total_rows_query = "SELECT COUNT(*) as total_rows FROM table_name";
$total_rows_result = mysqli_query($conn, $total_rows_query);
$total_rows = mysqli_fetch_assoc($total_rows_result)['total_rows'];
// Set pagination parameters
$limit = 10;
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$offset = ($page - 1) * $limit;
// Fetch paginated results
$results_query = "SELECT * FROM table_name LIMIT $limit OFFSET $offset";
$results_result = mysqli_query($conn, $results_query);
// Display paginated results
while ($row = mysqli_fetch_assoc($results_result)) {
// Display data
}
// Display pagination links
$total_pages = ceil($total_rows / $limit);
for ($i = 1; $i <= $total_pages; $i++) {
echo "<a href='?page=$i'>$i</a> ";
}
Related questions
-
HTML select elements value attribute
-
file_get_contents stripslashes saving images
-
GET parameters security vulnerabilities SQL injection