In what scenarios would it be more efficient to modify the SQL query to limit the number of results rather than using a while loop in PHP?
When dealing with large datasets, it is more efficient to limit the number of results directly in the SQL query rather than fetching all the data and then using a while loop in PHP to limit the output. By limiting the results in the SQL query, we reduce the amount of data transferred between the database and the PHP script, leading to better performance.
// Example of modifying the SQL query to limit the number of results
$sql = "SELECT * FROM table_name LIMIT 10";
$result = mysqli_query($connection, $sql);
while ($row = mysqli_fetch_assoc($result)) {
// Process each row here
}