<?php
final class MySQLiClass {
	private $mysqlic;
	
	public function __construct($hostname, $username, $password, $database) {
            $this->mysqlic = new mysqli($hostname, $username, $password, $database);
		
            if ($this->mysqlic->connect_error) {
                trigger_error('Error: Could not make a database link (' . $this->mysqlic->connect_errno . ') ' . $this->mysqlic->connect_error);
            }
		
            $this->mysqlic->query("SET NAMES 'utf8'");
            $this->mysqlic->query("SET CHARACTER SET utf8");
            $this->mysqlic->query("SET CHARACTER_SET_CONNECTION=utf8");
            $this->mysqlic->query("SET SQL_MODE = ''");
  	}	
		
  	public function query($sql) {               
		$query = $this->mysqlic->query($sql);

		if (!$this->mysqlic->errno) {
			if ($query instanceof mysqli_result) {
				$data = array();

				while ($row = $query->fetch_assoc()) {
					$data[] = $row;
				}

				$result = new stdClass();
				$result->num_rows = $query->num_rows;
				$result->row = isset($data[0]) ? $data[0] : array();
				$result->rows = $data;

				$query->close();

				return $result;
			} else {
				return true;
			}
		} else {
			throw new Exception('Error: ' . $this->mysqlic->error  . '<br />Error No: ' . $this->mysqlic->errno . '<br />' . $sql);
		}
  	}

	public function escape($value) {
            return $this->mysqlic->real_escape_string($value);
	}
	
  	public function countAffected() {
            return $this->mysqlic->affected_rows;
  	}

  	public function getLastId() {
            return $this->mysqlic->insert_id;
  	}	
	
	public function __destruct() {
            $this->mysqlic->close();
	}
}
?>