<?php
/**
 *  Database Manager
 * 
 *  @package Darion
 *  @author Arkadiusz 'ARJ' Jasak
 *  @copyright Copyright (c) 2006 Arkadiusz 'ARJ' Jasak (ajasak[at]gmail.com)
 *  @version 0.2
 */
class DBmanager{
	/**
	 * Object instance
	 *
	 * @var object
	 * @access private
	 */
	static private $thisInstance = null;
	
	/**
	 * Query results
	 *
	 * @var array
	 * @access private
	 */
	private $result = array();
	
	/**
	 * PDO instance
	 *
	 * @var object
	 * @access private
	 */
	private $dbh;
	
	/**
	 * Number of executes
	 *
	 * @access private
	 * @var int
	 */
	private $numExecutes = 0;
	
	/**
	 * Constructor
	 * Connect to database and set character encoding
	 * @access public
	 */
	public function __construct(){
		try{
			$this->dbh = new PDO(DB_KIND.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
			$this->dbh->exec('SET CHARACTER SET '.DB_CHARSET);
			$this->dbh->exec('SET collation_connection = '.DB_COLCON.';');
		}catch (PDOException $e){
			echo 'Error!: ' . $e->getMessage() . '<br/>';
		}
	}
	
	/**
	 * Query and fetch
	 *
	 * @param string $_query
	 * @param string $_mode
	 * @param int $_param
	 * @access public
	 * @return array
	 */
	public function queryandfetch($_query, $_mode, $_param = NULL){
		$this->numExecutes++;
		$this->result = null;
		$this->result = $this->dbh->query($_query);
	
		switch ($_mode){
			case 'assoc':
				return $this->result->fetchAll(PDO::FETCH_ASSOC);
			break;
			case 'both':
				return $this->result->fetchAll(PDO::FETCH_BOTH);
			break;
			case 'column':
				return $this->result->fetchAll(PDO::FETCH_COLUMN, $_param);
			break;
			default:
				return $this->result->fetchAll(PDO::FETCH_ASSOC);
		}
	}
	
	/**
	 * Exec: insert, update, delete
	 *
	 * @param string $_exec
	 * @access public
	 * @return int or false
	 */
	public function exec($_exec){
		$this->numExecutes++;
		$this->result = $this->dbh->exec($_exec);
		if($this->result == false){
			return false;
		}else{
			return $this->result;
		}
	}
	
	/**
	 * Count rows number
	 *
	 * @param string $_table
	 * @param string $_where
	 * @return int
	 */
	public function numRows($_table, $_where){
		$this->numExecutes++;
		$this->result = $this->dbh->query("SELECT COUNT(*) FROM ".$_table." WHERE ".$_where);
		return $this->result->fetchColumn();
	}
	
	/**
	 * Return number of executes
	 *
	 * @access public
	 * @return int
	 */
	public function numExecutes(){
		return $this->numExecutes;
	}
	
	/**
	 * Singleton
	 *
	 * @access public
	 * @return object
	 */
	static public function getInstance() {
		if(self::$thisInstance == null)
		{
			self::$thisInstance = new DBmanager();
		}
		return self::$thisInstance;
	}
	
	/**
	 * Destructor
	 * Close connection with database
	 * @access public
	 */
	public function __destruct(){
		$this->dbh = null;
	}
}
?>