<?php

class cDb {

	private $host, $user, $pass, $dbse;
	public $connected, $conn;

	function __construct($db_host, $db_user, $db_pass, $db_dbse) {
		$this->host = $db_host;
		$this->user = $db_user;
		$this->pass = $db_pass;
		$this->dbse = $db_dbse;
		$this->connected = FALSE;
		$this->conn = FALSE;
	}

	private function connect() {
		$dsn = "mysql:host=".$this->host.";port=3309;dbname=".$this->dbse;
		try {
			@$this->conn = new PDO($dsn, $this->user, $this->pass);
			$this->connected = TRUE;
		}
		catch (PDOException $e) {
			showErrorTemplate($e->getMessage());
		}
		
	}

	public function query($sql, $error = TRUE) {
		if (!$this->connected)
			$this->connect();
		try {
		 if (empty($sql))
			throw new Exception("Query was empty");
		//echo 'query: '. $sql.'<br>';
		if (!$stmt = $this->conn->query($sql)) {
			echo 'zla query :'.$sql.'<br>';
		}
		else {
			//echo 'dobra query :'.$sql.'<br>';
		}

		} catch (Exception $e) {
		if ($error){
			showErrorTemplate("db_query",$e->getMessage());
		}
		}
		return $stmt;
	}
	
	
	function queryWithBids($sql, $bids, $error = TRUE){
		if (!$this->connected)
			$this->connect();
		
		try {
			if (empty($sql))
				throw new Exception("Query was empty");
			//priprav statement
			$stmt = $this->conn->prepare($sql);
			//echo 'dobra queryWi :'.$sql.'<br>';
		
			$i=1;
			//nabinduj premenne
			foreach ($bids as &$value){
				$stmt->bindParam( $i, $value);
				$i++;
			}
			
			
			unset($value);
			
			if (!$stmt->execute())
				throw new Exception($sql . "Databaza nespustila query <br /><br />\n\n" );
			
		} catch (Exception $e) {
			if ($error)
				showErrorTemplate("db_query",$e->getMessage());
		}
		return $stmt;
	}
	
	public function numrows($q) {
		//$row = $q->fetch();
		return $q->rowCount();
	}
	
	public function dbnumrows($q) {
		return count(($this->query($q)->fetchAll()));
	}
	
	public function get($q) {
		$row = $q->fetch();
		//var_dump($row);
		return $row;
	}
	
	public function obtain($q, $arr=null) {
		//echo 'query Obtain: '. $q.'<br>';
		if (!empty($arr)){
		$q= $this->queryWithBids($q, $arr);
		$row = $q->fetch();
		return $row;
		}
		else {
			$q= $this->query($q);
			$row = $q->fetch();
			return $row;
		}
	}
	
	/* Neefektivne, pomale.. Pouzivat iba pri lenivosti */
	/*public function toArray($q) {
		$result = Array();
		if ($q) {
			$query = $this->query($q);
			if ($query)
				for ($i=0;$res=mysql_fetch_assoc($query);$i++)
					foreach($res as $key => $val)
						$result[$i][$key] = $val;
		}
		return $result;
	}*/
	
	public function getKey($key, $q, $returnDefault = "") {
		$res =$this->obtain($q);
		if (is_array($res))
			return $res[$key];
		
		return $returnDefault;
	}
	
	public function insertID() {
		return  $this->conn->lastInsertId();
	}
	
	public function disconnect() {
		if ($this->connected)
		{
			$this->conn = NULL;
			$this->connected= FALSE;
		}
	}
	
}

?>