How can the query function in the PHP code be improved to avoid errors related to mysqli_result objects?

When dealing with mysqli_result objects in PHP, it's important to check if the query was successful before trying to fetch data from it. To avoid errors related to mysqli_result objects, you can use the mysqli_num_rows() function to determine if there are any rows returned by the query. This way, you can avoid trying to fetch data from an empty result set.

// Check if the query was successful before trying to fetch data
$result = $conn->query("SELECT * FROM table_name");
if ($result && $result->num_rows > 0) {
    // Fetch data from the result set
    while ($row = $result->fetch_assoc()) {
        // Process the data
    }
} else {
    // Handle the case where no rows were returned
    echo "No rows found.";
}