What are best practices for organizing and structuring PHP code for database interactions?

When organizing and structuring PHP code for database interactions, it is best practice to separate concerns by using a dedicated class or set of classes for handling database operations. This helps in keeping the code clean, maintainable, and reusable. Additionally, using prepared statements to prevent SQL injection attacks and properly handling errors are crucial aspects of secure database interactions.

class Database {
    private $host = 'localhost';
    private $username = 'root';
    private $password = '';
    private $dbname = 'mydatabase';
    private $conn;

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

    public function query($sql) {
        $result = $this->conn->query($sql);
        if (!$result) {
            die("Error executing query: " . $this->conn->error);
        }
        return $result;
    }

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

    public function escape($value) {
        return $this->conn->real_escape_string($value);
    }

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