How can the DESC-LIMIT clause be used to retrieve specific rows from a database in PHP?
The DESC-LIMIT clause can be used in PHP to retrieve specific rows from a database by sorting the results in descending order and limiting the number of rows returned. This can be useful when you only need to fetch a certain number of records from a large dataset. By combining DESC with LIMIT, you can efficiently retrieve the desired subset of rows from the database.
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query to retrieve specific rows using DESC-LIMIT
$sql = "SELECT * FROM table_name ORDER BY column_name DESC LIMIT 5";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Column 1: " . $row["column1"]. " - Column 2: " . $row["column2"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();