<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
// +----------------------------------------------------------------------+
// | Singleton Database Class                                             |
// | File name : database.php                                             |
// | PHP version >= 5.2                                                   |
// +----------------------------------------------------------------------+
// | Author: BINU CHANDRAN.E<binu.chandran@armiasystems.com>              |
// +----------------------------------------------------------------------+
// | Copyrights Armia Systems � 2010                                      |
// | All rights reserved                                                  |
// +----------------------------------------------------------------------+
// | This script may not be distributed, sold, given away for free to     |
// | third party, or used as a part of any internet services such as      |
// | webdesign etc.                                                       |
// +----------------------------------------------------------------------+
class BaseModel
{
    /**
    * db instance
    * @var instance of AbstractDatabase
    **/
	protected $_db;
	/**
	* Table prefix
	* @var string
	**/
	public $tablePrefix;
        protected $db_connection;
    /**
    * Constructor
    **/
	public function __construct()
    {
        $this->_db = BaseDatabase::getInstance();
        $this->tablePrefix = MYSQL_TABLE_PREFIX;
        $this->db_connection=$this->_db->_connect();
    }

     final public function get_db_connection()
    {
        return $this->db_connection;
    }



    /**
    * Method to execute mysql queries
    * @param string $query
    **/
    final public function execute($query)
    {

        $res = mysqli_query($this->db_connection,$query) or die(mysqli_error($this->db_connection));
        return $res;
    }
    /**
    * Method to return the id of last  executed query
    * @param string $query
    * return integer
    **/
	final public function lastInsertId()
    {

        $res = mysqli_insert_id($this->db_connection);
        return $res;
    }
    /**
    * Method to fetch all rows from a result set
    * @param resource $resultSet
    * @return array $resultArray
    **/
	final public function fetchAll($resultSet)
	{
		$resultArray = array();
		while($obj = mysqli_fetch_object($resultSet))
		{
			$resultArray[] = $obj;
		}
        if(empty($resultArray)) {
            return array();
        }
        return $resultArray;
	}
     /**
    * Method to fetch result as pair from a result set
    * @param resource $resultSet
    * @return array $resultArray
    **/
	final public function fetchPair($resultSet)
	{
		$resultArray = array();
		while($obj = mysqli_fetch_array($resultSet, MYSQL_NUM))
		{
			$resultArray[$obj[0]] = $obj[1];
		}
		return $resultArray;
	}
	/**
    * Method to fetch one item from a result set
    * @param resource $resultSet
    * @return array $resultArray
    **/
	final public function fetchOne($resultSet)
	{

		$result = mysqli_fetch_array($resultSet, MYSQLI_NUM);
        return isset($result[0]) ? $result[0] : false;
	}
    /**
     * Method to get result set as an enumerated array
     * @param <type> $resultSet
     * @return <type> Enumerated array containing the query result
     */
    final public function fetchNumeric($resultSet){
        $resultArray  = array();
        while($obj = mysqli_fetch_row($resultSet)){
            $resultArray[] = $obj[0];
        }
        return $resultArray;
    }
    /**
    * Method to fetch single row from a result set
    * @param resource $resultSet
    * @return array $resultArray
    **/
	final public function fetchRow($resultSet)
	{
		$resultArray = array();
		while($obj = mysqli_fetch_object($resultSet))
		{
			$resultArray[] = $obj;
		}
        if(isset($resultArray[0])) {
            return $resultArray[0];
        }
		return $resultArray;
	}
	/**
	* Method to insert rows
	* @param string $table
	* @param array $data
	**/
    final public function insert($table, array $data)
    {
        $query = 'INSERT INTO ' . $table . ' SET ';
        $query .= $this->_buildQueryString($data);
 //echo $query;exit;
        $this->execute($query);
		return mysqli_insert_id($this->db_connection);
    }
	/**
	* Method to update table
	* @param string $table
	* @param array $data
	* @param string $where
	**/
    final public function update($table, array $data, $where)
    {
        $query = 'UPDATE ' . $table . ' SET ';
        $query .= $this->_buildQueryString($data);
        $query .= ' WHERE '.$where;
        $this->execute($query);
        return $this->hasAffected();
    }
    /**
     * function to print the query
     * @param <type> $type
     * @param <type> $table
     * @param array $data
     * @param <type> $where
     * @param <type> $stop
     */
    final public function printQuery($type, $table, array $data = array(), $where = '', $stop = '' ){
        if(strtolower($type) == 'insert'){
            $query = 'INSERT INTO ' . $table . ' SET ';
            $query .= $this->_buildQueryString($data);
        }else if(strtolower($type) == 'update'){
            $query = 'UPDATE ' . $table . ' SET ';
            $query .= $this->_buildQueryString($data);
            $query .= ' WHERE ' . $where;
        }else if(strtolower($type) == 'delete'){
            $query = 'DELETE FROM ' . $table;
            $query .= ' WHERE ' . $where;
        }
         //echo $query;
         if($stop != ''){
             exit;
         }
    }
	/**
	* Method to delete rows from table
	* @param string $table
	* @param array $data
	* @param string $where
	**/
    final public function delete($table, $where)
    {
        $query = 'DELETE FROM ' . $table;
        $query .= ' WHERE ' . $where;
        $this->execute($query);
        return $this->hasAffected();
    }
	/**
	* Method to get status has affected
	**/
    final public function hasAffected()
    {
        return mysqli_affected_rows($this->db_connection) > 0;
    }
	/**
	* Method to get number of rows affected
	**/
    final public function affectedRows()
    {
        return mysqli_affected_rows($this->db_connection);
    }
	/**
	* Method to build mysql query string from an array
	* @param array $data
	**/
    private function _buildQueryString(array $data)
    {
        $columnCount    = count($data);
        $currentColumn  = 1;
		$query = '';
        foreach ($data as $column => $value) {
            $query .= $column . ' = "' . $value.'"';
            if ($currentColumn++ <  $columnCount) {
                $query .= ', ';
            }
        }
        return $query;
    }
    final public function fetchAllList($resultSet)
	{
		$result = mysqli_fetch_array($resultSet);
        return isset($result[0]) ? $result[0] : false;
	}
    /**
     *
     * Method to escape the string input by the user
     * @param string $data
     * @return $data
     */
    final public function escapeString($data)
    {
       return mysqli_real_escape_string($this->db_connection, $data) ;
    }




   	public  function dopaging($sql,$numrecords=0,$limit=15,$pagestart=0)
	{
 	$temp = mysqli_query($this->db_connection,$sql) or die(mysqli_error());
	$numrows = mysqli_num_rows($temp);
	$start = LibPager::findStart($limit,$numrows);
	if ($numrecords == 0)
	  LibPager::$pages = LibPager::findPages($numrows, $limit);
	else{
	if ($numrows > $numrecords)
	  LibPager::$pages = LibPager::findPages($numrecords, $limit);
	else
	 LibPager:: $pages = LibPager::findPages($numrows, $limit);
	}
	if ($numrecords == 0)
	  $sql1 = $sql . " LIMIT " . $start. ", ". $limit ;
	else{
	 if (($start + $limit) > $numrecords)
	   $sql1 = $sql . " LIMIT " . $start. ", ". ($numrecords - $start);
	 else
	   $sql1 = $sql . " LIMIT " . $start. ", ". $limit ;
	}
 		return $sql1;

	}

        function checkTableExist($table)
	{
		$query="SHOW TABLES LIKE '".$table."'" ;
		$result=$this->execute($query);
		if($this->fetchRow($result))
			return 1;
		else
			return 0;
	}
        function selectResultFrom($table,$field,$where)
	{
		if($where!='')
			$where= ' WHERE '.$where;
		$query = "SELECT ".$field."
    	          FROM ".$table.$where ;

		$res = $this->execute($query);
		return $this->fetchAll($res);
	}


}
?>