How can you limit the number of results per page in a MySQL query in PHP?
To limit the number of results per page in a MySQL query in PHP, you can use the LIMIT clause in your SQL query. This allows you to specify the number of rows to return from the query. By combining the LIMIT clause with a calculation based on the current page number and the desired number of results per page, you can effectively paginate your results.
// Define the number of results per page
$results_per_page = 10;
// Calculate the offset based on the current page number
if(isset($_GET['page'])){
$page = $_GET['page'];
} else {
$page = 1;
}
$offset = ($page - 1) * $results_per_page;
// Construct and execute the SQL query with the LIMIT clause
$sql = "SELECT * FROM your_table LIMIT $offset, $results_per_page";
$result = mysqli_query($conn, $sql);
// Fetch and display the results
while($row = mysqli_fetch_assoc($result)){
// Output the results
}