What best practices should be followed when querying a database in PHP to prevent errors like the one mentioned in the thread?

Issue: To prevent errors when querying a database in PHP, it is crucial to properly handle potential errors such as empty result sets. One way to address this is by checking if the query returned any rows before attempting to access the data.

// Connect to the database
$connection = new mysqli("localhost", "username", "password", "database");

// Check connection
if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}

// Query the database
$result = $connection->query("SELECT * FROM table");

// Check if any rows were returned
if ($result->num_rows > 0) {
    // Fetch and display the data
    while ($row = $result->fetch_assoc()) {
        echo "Name: " . $row["name"] . "<br>";
    }
} else {
    echo "No results found.";
}

// Close the connection
$connection->close();