How can DESC LIMIT be used to retrieve specific entries in a PHP database query?
To retrieve specific entries in a PHP database query using DESC LIMIT, you can use the DESC keyword to sort the results in descending order and the LIMIT keyword to specify the number of entries to retrieve. This can be useful for fetching the latest entries or a specific range of entries from a database table.
<?php
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query to retrieve specific entries using DESC LIMIT
$sql = "SELECT * FROM myTable ORDER BY id DESC LIMIT 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Keywords
Related Questions
- How can the use of sessions and cookies in PHP prevent users from resubmitting forms when navigating back in the browser history?
- How can PHP developers ensure accurate tracking of user activity within a specified time frame?
- How can PHP be used to display dynamic content based on user input in a form?