What is the best way to handle empty query results in PHP?
When querying a database in PHP, it is common to encounter empty results, especially when using SELECT queries. To handle this situation, you can check if the result set is empty and then take appropriate action, such as displaying a message to the user or performing a different query.
// Perform a SELECT query
$query = "SELECT * FROM table WHERE condition";
$result = mysqli_query($connection, $query);
// Check if the result set is empty
if(mysqli_num_rows($result) == 0) {
echo "No results found.";
} else {
// Process the results
while($row = mysqli_fetch_assoc($result)) {
// Do something with each row
}
}
// Free the result set
mysqli_free_result($result);
Keywords
Related Questions
- What are the best practices for retrieving GET and POST parameters in PHP?
- What are common pitfalls when integrating a third-party chat system with PHP sessions?
- How can errors related to including files in PHP be resolved, especially when dealing with sensitive information like MySQL access credentials?