What are the best practices for sorting and limiting SQL queries in PHP to retrieve specific data from a database?
When retrieving data from a database using SQL queries in PHP, it is important to properly sort and limit the results to ensure efficient data retrieval and processing. To achieve this, you can use the ORDER BY clause to sort the data based on a specific column and the LIMIT clause to restrict the number of rows returned by the query.
// Example SQL query to retrieve data sorted by 'column_name' and limited to 10 rows
$sql = "SELECT * FROM table_name ORDER BY column_name LIMIT 10";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
// Process retrieved data here
}
} else {
echo "No results found";
}