How can the query() function in PHP be properly utilized to avoid returning empty content from the database?
To avoid returning empty content from the database when using the query() function in PHP, you should check if the query returned any rows before processing the results. This can be done by checking the number of rows returned using functions like mysqli_num_rows() or rowCount() depending on the database extension being used. If no rows are returned, you can handle the empty result set appropriately, such as displaying a message to the user.
// Assuming $conn is the database connection object
$query = "SELECT * FROM table_name WHERE condition";
$result = $conn->query($query);
if ($result->num_rows > 0) {
// Process the results
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
} else {
echo "No results found.";
}