What are some best practices for handling database connections in PHP projects?

When working on PHP projects that require database connections, it's important to follow best practices to ensure efficient and secure handling of connections. One common approach is to use a database class to manage connections and queries, allowing for better organization and reusability of code.

class Database {
    private $host = 'localhost';
    private $username = 'username';
    private $password = 'password';
    private $database = 'database';
    private $conn;

    public function __construct() {
        $this->conn = new mysqli($this->host, $this->username, $this->password, $this->database);
        if ($this->conn->connect_error) {
            die("Connection failed: " . $this->conn->connect_error);
        }
    }

    public function query($sql) {
        return $this->conn->query($sql);
    }

    public function close() {
        $this->conn->close();
    }
}

// Example usage
$db = new Database();
$result = $db->query("SELECT * FROM users");
while ($row = $result->fetch_assoc()) {
    echo $row['username'] . "<br>";
}
$db->close();