<?php
class mysql_stmt {
    private $dbh = false;
    private $binds = array();
    private $prefix = "";
    private $insertid = false;
    public $result = false;
    public $query = "";

    public function __construct($dbh, $query, $prefix) {
        $this->dbh = $dbh;
        $this->query = $query;
        $this->prefix = $prefix;
        $this->result = false;
        $this->binds = array();
    }

    public function execute() {
        $binds = func_get_args();
        $query = str_replace(":pfx:", $this->prefix, $this->query);

        $this->binds = $binds;

        $translate = array();
        foreach ($binds as $key => $value) {
            $translate[':' . ($key+1)] = "'" . mysql_real_escape_string($value, $this->dbh) . "'";
            $translate[';' . ($key+1)] = mysql_real_escape_string($value, $this->dbh);
        }
        $query = strtr($query, $translate);

        $this->result = mysql_query($query, $this->dbh);
        if (!$this->result) {
            throw new Exception("Error executing MySQL-Query (".mysql_errno($this->dbh) . "): " . mysql_error($this->dbh));
        }
        $this->insertid = mysql_insert_id($this->dbh);
        return $this;
    }

    public function fetch_assoc() {
        return mysql_fetch_assoc($this->result);
    }

    public function single_field() {
        $fetch = mysql_fetch_row($this->result);
        return $fetch[0];
    }

    public function fetch_all() {
        $return = array();
        while ($row = $this->fetch_assoc()) {
            $return[] = $row;
        }
        return $return;
    }

    public function num_rows() {
        return mysql_num_rows($this->result);
    }

    public function affected_rows() {
        return mysql_affected_rows($this->dbh);
    }

    public function insertId() {
        return $this->insertid;
    }

    public function single_column($column = NULL) {
        $return = array();
        while ($row = mysql_fetch_array($this->result)) {
            $return[] = $row[ ($column !== NULL ? $column : 0)];
        }
        return $return;
    }
}
?>