<?php
class mysql {
    private $user;
    private $pw;
    private $db;
    private $host;
    private $dbh;
    private $prefix;

    public function __construct($host, $user, $pw, $db, $prefix = "") {
        $this->host = $host;
        $this->user = $user;
        $this->pw = $pw;
        $this->db = $db;
        $this->prefix = $prefix;

        $this->connect();
    }

    public function __destruct() {
        if (is_resource($this->dbh))
           mysql_close($this->dbh);
    }

    private function connect() {
        $this->dbh = mysql_connect($this->host, $this->user, $this->pw, true);
        if (!is_resource($this->dbh)) {
            throw new Exception("Couldn't connect to MySQL databas; Error ".mysql_errno() . ": " . mysql_error());
        }
        if (!mysql_select_db($this->db, $this->dbh)) {
            throw new Exception("Couldn't select MySQL database; Error ".mysql_errno() . ": ".mysql_error($this->dbh));
        }
    }

    public function prepare($query) {
        if (!is_resource($this->dbh) || !$this->ping()) {
            $this->connect();
        }

        return new mysql_stmt($this->dbh, $query, $this->prefix);
    }

    public function ping() {
        return mysql_ping($this->dbh);
    }
}
?>