How can the LIMIT clause in a MySQL query be utilized to navigate through records?
The LIMIT clause in a MySQL query can be utilized to navigate through records by specifying the number of records to retrieve and the starting point. This can be useful for implementing pagination on a website, where only a certain number of records are displayed on each page.
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Query to retrieve records with LIMIT for pagination
$page = 1; // Current page number
$records_per_page = 10; // Number of records to display per page
$offset = ($page - 1) * $records_per_page; // Calculate offset
$sql = "SELECT * FROM table_name LIMIT $offset, $records_per_page";
$result = $conn->query($sql);
// Loop through the results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// Display record data
}
} else {
echo "0 results";
}
// Close the connection
$conn->close();