What are some common pitfalls when implementing pagination in PHP for displaying database results?
One common pitfall when implementing pagination in PHP for displaying database results is not properly sanitizing user input, which can lead to SQL injection attacks. To solve this issue, always sanitize user input before using it in database queries. Another pitfall is not calculating the correct offset for pagination, resulting in incorrect data being displayed. To avoid this, calculate the offset based on the current page number and limit per page.
// Sanitize user input
$page = isset($_GET['page']) ? filter_var($_GET['page'], FILTER_SANITIZE_NUMBER_INT) : 1;
// Calculate offset
$limit = 10; // Results per page
$offset = ($page - 1) * $limit;
// Use offset and limit in your database query
$query = "SELECT * FROM table_name LIMIT $offset, $limit";
// Execute the query and display results