What is the purpose of using the DESC-LIMIT clause in a SQL query in PHP?
The DESC-LIMIT clause in a SQL query in PHP is used to retrieve a specific number of rows from a table in descending order. This can be helpful when you want to display the latest or most recent records first in your application. By using DESC-LIMIT, you can control the number of rows returned and ensure that only the necessary data is fetched.
// 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);
}
// SQL query with DESC-LIMIT clause
$sql = "SELECT * FROM table_name ORDER BY column_name DESC LIMIT 10";
// Execute the query
$result = $conn->query($sql);
// Fetch and display the results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
// Close the connection
$conn->close();
Keywords
Related Questions
- What are some potential pitfalls to be aware of when using the mysql_fetch_array function in PHP?
- What are some potential pitfalls to avoid when designing a PHP-based friendship system with bidirectional relationships?
- What are some potential pitfalls of mixing mysql_ and mysqli functions in PHP code?