What best practices should be followed when handling database connections and queries in PHP to avoid errors like "Datenbank nicht erreichbar"?

When handling database connections and queries in PHP, it is important to properly handle errors to avoid issues like "Datenbank nicht erreichbar" (Database not reachable). To prevent this error, you should always check the connection status before executing queries and handle any potential errors gracefully by using try-catch blocks.

<?php

// Database connection parameters
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

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

// Execute query
try {
    $sql = "SELECT * FROM table";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // Output data
        while($row = $result->fetch_assoc()) {
            echo "id: " . $row["id"] . " - Name: " . $row["name"];
        }
    } else {
        echo "0 results";
    }
} catch (Exception $e) {
    echo "Error executing query: " . $e->getMessage();
}

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

?>