<?php 

include 'config.php';
class database{
	
	public $db_conn;
	private $query; 
	
	function __construct($server,$username,$password,$database){
		$this->db_conn = mysqli_connect($server,$username,$password,$database) or
		mysqli_select_db($this->db_conn,DB_DATABASE);
	}
	public function prepare($query) {
        return mysqli_prepare($this->db_conn, $query);
    }
	
	public function query($query){
	
		// $this->query = mysqli_query($this->db_conn,$query);
		$result = mysqli_query($this->db_conn,$query);
		return $result;
		
	}   
	public function insert($table, array $data){
	
		$query = "INSERT INTO {$table} SET ".$this->array_to_query( ", ", $data );
		mysqli_query($this->db_conn,$query);
		return mysqli_insert_id($this->db_conn);
		
	}
	public function update($table, $data, $where = array()){
		
		$query = "UPDATE {$table} SET ".$this->array_to_query( ", ", $data ). " where ".$this->array_to_query( " and ", $where );
		$query_result	= mysqli_query($this->db_conn,$query);
		return $query_result;
		
	}
	public function delete($table, $where = array()){
		
		$query = "DELETE from {$table} where ".$this->array_to_query( " and ", $where );
		mysqli_query($this->db_conn,$query);
		
	}
	
	public function array_to_query($operator,$data){
	
		return str_replace("+"," ", str_replace("&", "\" {$operator} ", str_replace("=", "=\"",urldecode(http_build_query($data))))). "\"";
	
	}
	public function select($table, $select = '*', $where = array()){
		
		$query = "select ".$select." from ".$table;
		
		if(count($where)){
			$query .= " WHERE ".$this->array_to_query(" AND ",$where);
		}
		$return = array();
		$result = mysqli_query($this->db_conn,$query);
		if(mysqli_num_rows($result))
			while($row = mysqli_fetch_assoc($result))
				$return[] = $row;
		
		return  count($return) > 1 ? $return : $return[0];
	}
	public function get($data=array()){
	
		$query = "";
		if(array_key_exists("type",$data) && array_key_exists("where",$data)){
			$data["where"]["type"] = $data["type"];
			$query ="select * from ".$data["table"]." where ".$this->array_to_query("",$data["where"]);
		} else if(array_key_exists("where",$data)){
			$query ="select * from ".$data["table"]." where ".$this->array_to_query("",$data["where"]);
		} else {
			$query ="select * from ".$data["table"];
		}
		
		if(array_key_exists("query",$data)){
			$query = $data["query"];
		}
		
		$new_array = array();
		$result = mysqli_query($this->db_conn,$query);
		
		while ($row=mysqli_fetch_assoc($result)) {
			$new_array[] = $row;
		}
		return  $new_array;
	
	}
  
  	public function getSingleColumn($table, $select, $where = array()){
	
		$query = "select ".$select." from ".$table;
		
	if(count($where)){
		$query .= " WHERE ".$this->array_to_query(" AND ",$where);
	}
		
    $res = mysqli_query($this->db_conn,$query);

    if ($row = mysqli_fetch_assoc($res))

        return $row[$select];
    }
}

$db = new database(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>