In the provided PHP script, what potential pitfalls or inefficiencies can be identified, such as the DB query being unnecessarily inefficient?
The potential inefficiency in the provided PHP script is that the DB query is being executed inside a loop, resulting in multiple queries being sent to the database unnecessarily. To solve this issue, we can retrieve all the data in a single query and then iterate over the results in the loop.
// Retrieve all data in a single query
$query = "SELECT * FROM users";
$result = mysqli_query($connection, $query);
// Check if the query was successful
if($result) {
// Iterate over the results in a loop
while($row = mysqli_fetch_assoc($result)) {
// Process each row here
}
} else {
echo "Error: " . mysqli_error($connection);
}
// Free the result set
mysqli_free_result($result);