<?php

class DBOperation 
{
    var $_dbConn;
    var $_queryResource;
    
    function __DBOperation()
    {
        //do nothing
    }
    
    function connect_db($host, $user, $pwd, $dbname)
    {
        $dbConn = mysqli_connect($host, $user, $pwd, $dbname);
        if (!$dbConn) {
            echo "Error: Unable to connect to MySQL." . PHP_EOL;
            echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
            echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
            exit;
        }
        mysqli_query($dbConn, "SET NAMES utf8");
        $this->_dbConn = $dbConn;

        mysqli_query($dbConn, "SET NAMES 'utf8'");
        mysqli_query($dbConn, "SET CHARACTER_SET_CLIENT='utf8'");
        mysqli_query($dbConn, "SET CHARACTER_SET_RESULTS='utf8'");
        return true;
    }
    
    function query($sql)
    {
        if (!$queryResource = mysqli_query($this->_dbConn, $sql))
            die ("MySQL Query Error");
        $this->_queryResource = $queryResource;
        return $queryResource;        
    }
    
    /** Get array return by MySQL */
    function fetch_array()
    {
        return mysqli_fetch_array($this->_queryResource, MYSQLI_ASSOC);
    }
    
    function get_num_rows()
    {
        return mysqli_num_rows($this->_queryResource);
    }
    
    function fetch_row()
    {
        return mysqli_fetch_row($this->_queryResource);
    }
    
    function fetch_all()
    {
        return mysqli_fetch_all($this->_queryResource, MYSQLI_ASSOC);
    }

    function fetch_assoc()
    {
        return mysqli_fetch_assoc($this->_queryResource, MYSQLI_ASSOC);
    }
    /** Get the cuurent id */    
    function get_insert_id()
    {
        return mysqli_insert_id($this->_dbConn);
    }
    
    function close_db()
    {
        if ($this->_dbConn != null) {
            mysqli_close($this->_dbConn);
      }
    }
    
    function mysql_real_escape_string($str)
    {
        return mysqli_real_escape_string($this->_dbConn, $str);
    }
}
?>