<?

/**
 * ######################################################################################################################
 * #																	# Warning, please do not Modify this header, 	#
 * # Database class to help you connect to a mysql database with ease.	# it is here to help others same like you.		#
 * # Version 0.1 beta, use at your own risk.							# So please, be nice so that others can enjoy 	#
 * # To see more nice code, visit my blog at www.3wphp.com... Good luck.# The same freedom as you have.					#
 * # Mannny E.															# Always a pleasure,	Manny E.				#
 * # ####################################################################################################################
 * # -------------------------------------------------------------------------------------------------------------------#
 * # Developed by Manny E. for questions use the contact form at www.3wcorner.com.										#
 * # ===================================================================================================================#
 * # I always try to make things easier for the novice out there, so please if you have any comments suggestions, or 	#
 * # Questions, please post your comment on 3wphp.com, or, use the contact us form at 3wcorner.com.						#
 * # Happy coding guys,																									#
 * # Manny.																												#
 * # -------------------------------------------------------------------------------------------------------------------#
 * ######################################################################################################################
 *
 * usage:
 * ----------------------------------------------
 * initiate the class usually with $db = new db();
 * then you need to configure your DB connection parammeters, and this is how you do it.
 *
 *
 */
class db
{

	public $data;
	
	public $debug = true;

	protected $host = 'localhost';

	protected $port = 3306;

	protected $user = '';

	protected $pass = '';

	protected $name = '';

	protected $link = false;

	protected $conn = false;

	public $logging = true;

	public $connected = false;

	public $configured = false;

	public $errors = array();

	public $last_sql = false;

	public $count = false;
	
	// Query vars
	public $action = 'select';

	public $table = false;

	public $what = false;

	public $where = array();

	public $where_like = array();

	public $group = false;

	public $limit = false;

	public $order_by = false;

	public $order = 'ASC';

	public $res = false;

	public $results;

	public $duplicate = false;

	public $duplicate_what = '';

	function __construct()
	{}

	function load($info = false)
	{
		// var_dump($info);die();
		if (! $this->configured){
			$this->set($info);
		}
		if (! $this->link){
			$this->connect();
		}
		if (empty($this->errors)){
			return true;
		}
		die('DB Connection Failed!');
		return false;
	}

	function connect()
	{
		if (! $this->configured){
			$this->error('Connection parammeters were not configured.');
			return false;
		}
		$this->link = @mysql_connect($this->host, $this->user, $this->pass);
		$this->connected = $this->connected();
		if ($this->connected){
			$this->db_select();
		}
		else{
			die('could not connect to DB');
		}
	}

	function db_select()
	{
		if (empty($this->name)){
			return false;
		}
		mysql_select_db($this->name);
	}

	function set($info)
	{
		if (! $info){
			return false;
		}
		
		if (empty($info->host)){
			$this->errors[] = 'DB Host not defined';
		}
		if (empty($info->user)){
			$this->errors[] = 'DB Username not defined';
		}
		if (! isset($info->pass)){
			$this->errors[] = 'DB Password not defined';
		}
		if (empty($info->name)){
			$this->errors[] = 'DB Name not defined';
		}
		if (! empty($this->errors)){
			return $this->errors;
		}
		
		$this->host = $info->host;
		$this->user = $info->user;
		$this->pass = $info->pass;
		$this->name = $info->name;
		$this->configured = true;
		return true;
	}

	function connected()
	{
		return is_resource($this->link);
	}

	function show_tables()
	{
		$this->action = 'show tables';
		return $this;
	}

	function alter_table($table_name)
	{
		$this->action = 'alter table';
		$this->table = $table_name;
		return $this;
	}

	function drop($item, $type = 'table')
	{
		if ($type == 'table'){
			$this->action = 'DROP TABLE';
		}
		else{
			return false;
		}
		$this->table = $item;
		return $this;
	}

	function like($like)
	{
		$this->like = $like;
		return $this;
	}

	function get()
	{
		$res = false;
		if (strtolower($this->action) == 'select' && ! $this->table){
			return false;
		}
		if (strtolower($this->action) == 'select'){
			$sql = strtoupper($this->action) . ' ' . $this->what . ' FROM ' .
					 $this->table;
			$x = 0;
			if (! empty($this->where)){
				$where_str = ' WHERE ';
				
				foreach ($this->where as $where){
					if ($x > 0){
						$where_str .= ' AND ';
					}
					if (isset($where->operator)){
						$where_str .= $where->field . $where->operator .
								 $where->value . ' ';
					}
					else{
						$where_str .= $where->field . ' = ' . $where->value . ' ';
					}
					$x ++;
				}
				$sql .= $where_str;
			}
			if (! empty($this->where_like)){
				$where_str = ' ' . (isset($where_str{0}) ? ' ' : ' WHERE ');
				//$x = 0;
				foreach ($this->where_like as $where_like){
					if ($x > 0){
						$where_str .= ' AND ';
					}
					$where_str .= $where_like->field . ' LIKE ' .
							 $where_like->value . ' ';
					$x ++;
				}
				$sql .= $where_str;
			}
			if ($this->group){
				$sql .= ' GROUP BY ' . $this->group;
			}
			if ($this->order_by){
				$sql .= ' ORDER BY ' . $this->order_by . ' ' . $this->order;
			}
			
			if ($this->limit){
				$sql .= ' LIMIT ' . $this->limit;
			}
			
			// var_dump($sql);die();
			$res = $this->query($sql);
			
			if ($res){
				$this->res = $res;
				$this->count = $this->num_rows($this->res);
			}
			else{
				$this->count = 0;
			}
			$this->reset();
			return $this;
		}
		elseif (strtolower($this->action) == 'show tables'){
			$sql = strtoupper($this->action);
			if (! empty($this->like)){
				$like_str = ' LIKE "' . $this->like . '"';
				$sql .= $like_str;
			}
			$res = $this->query($sql);
			
			if ($res){
				$this->res = $res;
				$this->count = $this->num_rows($this->res);
			}
			else{
				$this->count = 0;
			}
			$this->reset();
			return $this;
		}
		elseif (strtolower($this->action) == 'alter table'){
			$sql = strtoupper($this->action);
			if (! empty($this->order_by)){
				$like_str = ' ORDER BY `' . $this->order_by . '';
				$sql .= $like_str;
			}
			
			$res = $this->query($sql);
			
			if ($res){
				$this->res = $res;
				$this->count = $this->num_rows($this->res);
			}
			else{
				$this->count = 0;
			}
			$this->reset();
			return $this;
		}
		elseif (strtolower($this->action) == 'drop table'){
			$sql = strtoupper($this->action) . ' IF EXISTS ' . $this->table;
			$res = $this->query($sql);
			
			if ($res){
				$this->res = $res;
			}
			else{
				$this->count = 0;
			}
			$this->reset();
			return $this;
		}
		$this->reset();
		return false;
	}

	function reset()
	{
		$this->action = 'select';
		$this->table = false;
		$this->what = false;
		$this->where = array();
		$this->where_or = array();
		$this->where_like = array();
		$this->group = false;
		$this->limit = false;
		$this->order_by = false;
		$this->order = 'ASC';
		$this->duplicate = false;
		return;
	}

	function reset_all()
	{
		$this->action = 'select';
		$this->table = false;
		$this->what = false;
		$this->where = array();
		$this->group = false;
		$this->limit = false;
		$this->order_by = false;
		$this->order = 'ASC';
		$this->res = false;
		$this->duplicate = false;
		return;
	}

	function result()
	{
		$this->results = array();
		$results = $this->fetch($this->res);
		if ($this->count == 1){
			$this->results[] = $results;
		}
		else{
			$this->results = $results;
		}
		
		$this->reset_all();
		
		return $this->results;
	}

	function sort($by = 'id')
	{}

	function order_by($field, $order = 'ASC',$escape = true)
	{
		if (empty($field)){
			$this->error('Empty field given in $this->order_by!');
			return false;
		}
		if($escape)
		{
			$field = '`'.trim($field).'`';
		}
		$this->order_by = $field;
		$this->order = $order;
		return $this;
	}

	function group_by($field = false)
	{
		if (empty($field)){
			$this->error('Empty field given in $db->group_by');
			return false;
		}
		$this->group = $field;
		return $this;
	}

	function limit($limit = 30, $start = 0)
	{
		$this->limit = $start . ',' . $limit;
		return $this;
	}

	function query($sql)
	{
		$this->last_sql = $sql;
		/*
		 * if ($this->logging == true) { $this->sql_log[] = $sql; }
		 */
		$res = mysql_query($sql, $this->link);// or die(mysql_error());
		//var_dump(mysql_error());die;
		$err = mysql_error($this->link);
		if (! is_resource($res) && !empty($err) )
		{
			$this->error('SQL Query failed' . "\n<br />" . $sql ."<br />\nMySql Error:".mysql_error()."<br />\n". '<br />');
			$this->reset();
			if($this->debug)
			{
				echo '<pre>';
				var_dump($this->errors);
				debug_print_backtrace();
				echo '</pre>';
				die;
			}
			return false;
		}
		
		// var_dump($res);die();
		return $res;
	}

	function affected()
	{
		return mysql_affected_rows($this->link);
	}

	function insert($table, $data = false, $escape = true)
	{
		if (empty($table)){
			return false;
		}
		$fileds = array();
		$values = array();
		$insert_id = false;
		
		if (strtoupper($this->duplicate) == 'IGNORE'){
			$sql = 'INSERT IGNORE INTO ' . $table . '';
		}
		else{
			$sql = 'INSERT INTO ' . $table . "\n";
		}
		
		if (! empty($data)){
			foreach ($data as $key => $val){
				if ($escape){
					$fileds[] = "\t" . '`' . $key . '`' . "\n";
					
					if($val === NULL)
					{
						$values[] = "\t" . 'NULL' . "\n";
					}
					else 
					{
						$val = mysql_real_escape_string($val);
						$values[] = "\t" . '"' . $val . '"' . "\n";
					}
				}
				else{
					$fileds[] = $key;
					$values[] = $val;
				}
			}
			$sql .= '(' . implode(',', $fileds) . ') ';
			$sql .= 'VALUES (' . implode(',', $values) . ')';
		}
		
		if ($this->duplicate){
			if (! empty($this->duplicate_what)){
				$sql .= ' ON DUPLICATE KEY ' . strtoupper($this->duplicate) . ' ';
				if (strtoupper($this->duplicate) == 'UPDATE'){
					foreach ($this->duplicate_what as $f => $v){
						if ($escape){
							$v = mysql_real_escape_string($v);
							$update[] = '`' . $f . '` = "' . $v . '"';
						}
						else{
							$update[] = $f . ' = ' . $v;
						}
					}
					$sql .= implode(',', $update);
				}
			}
			else{
				
				if (strtoupper($this->duplicate) == 'IGNORE'){
					// $sql .= ' ON DUPLICATE KEY
				// '.strtoupper($this->duplicate).' ';
				}
			}
			
			$res = $this->query($sql);
			$affected = mysql_affected_rows($this->link);
			if ($affected !== false){
				$this->reset();
				return true;
			}
		}
		else{
			$res = $this->query($sql);
			$insert_id = mysql_insert_id($this->link);
			if ($insert_id){
				$this->reset();
				return $insert_id;
			}
		}
		$this->reset();
		
		return false;
	}

	function update($table, $data = false, $escape = true, $debug = false)
	{
		if (empty($table)){
			return false;
		}
		$fileds = array();
		$values = array();
		$insert_id = false;
		$sql = 'UPDATE ' . $table . ' ';
		
		if (! empty($data)){
			$sql .= ' SET ';
			foreach ($data as $f => $v){
				if ($escape){
					if($v === NULL)
					{
						$update[] = '`' . $f . '` = NULL ';
					}
					else
					{
						$v = mysql_real_escape_string($v);
						$update[] = '`' . $f . '` = "' . $v . '"';
					}
				}
				else{
					$update[] = $f . ' = ' . $v;
				}
			}
			$sql .= implode(',', $update);
		}
		if (! empty($this->where)){
			$where_str = ' WHERE ';
			$x = 0;
			foreach ($this->where as $where){
				if ($x > 0){
					$where_str .= ' AND ';
				}
				if (isset($where->operator)){
					$where_str .= $where->field . $where->operator .
							 $where->value . ' ';
				}
				else{
					$where_str .= $where->field . ' = ' . $where->value . ' ';
				}
				$x ++;
			}
			$sql .= $where_str;
		}
		
		if ($debug){
			var_dump($sql);
			die();
		}
		$res = $this->query($sql);
		
		$affected = mysql_affected_rows($this->link);
		if ($affected){
			$this->reset();
			return $affected;
		}
		$this->reset();
		return false;
	}

	function delete($table, $limit = false)
	{
		if (empty($table)){
			return false;
		}
		$fileds = array();
		$values = array();
		$insert_id = false;
		$sql = 'DELETE FROM ' . $table . ' ';
		
		if (! empty($this->where)){
			$where_str = ' WHERE ';
			$x = 0;
			foreach ($this->where as $where){
				if ($x > 0){
					$where_str .= ' AND ';
				}
				if (isset($where->operator)){
					$where_str .= $where->field . $where->operator .
							 $where->value . ' ';
				}
				else{
					$where_str .= $where->field . ' = ' . $where->value . ' ';
				}
				$x ++;
			}
			$sql .= $where_str;
		}
		
		if ($limit){
			$sql .= ' LIMIT ' . $limit;
		}
		$res = $this->query($sql);
		$this->reset();
		return true;
	}

	function on_duplicate($what = array(), $action = 'update')
	{
		$this->duplicate_what = $what;
		$this->duplicate = $action;
		return $this;
	}

	function fetch($res = false)
	{
		if (empty($res) && empty($this->res)){
			$this->count = 0;
			return array();
		}
		elseif (empty($res) && ! empty($this->res)){
			$res = $this->res;
		}
		$this->count = $this->num_rows($res);
		// var_dump($count);die();
		if ($this->count == 0){
			return array();
		}
		
		$data = new stdClass();
		if ($this->count > 1){
			$ret_rows = array();
			while ($row = mysql_fetch_assoc($res)){
				$data = new stdClass();
				foreach ($row as $field => $val){
					$data->{$field} = $val;
				}
				$ret_rows[] = $data;
			}
			$this->reset();
			return $ret_rows;
		}
		else{
			$rows = mysql_fetch_assoc($res);
			if (! $rows){
				$this->errors[] = 'SQL Query failed';
				$this->reset();
				return false;
			}
			foreach ($rows as $field => $row){
				$data->{$field} = $row;
			}
			$this->reset();
			return $data;
		}
		return $res;
	}

	function fetch_row($res)
	{
		if (! is_resource($res)){
			return false;
		}
		
		$count = $this->num_rows($res);
		if ($count > 0){
			$data = false;
			
			$row = mysql_fetch_assoc($res);
			foreach ($row as $key => $val){
				if (! is_object($data)){
					$data = new stdClass();
				}
				$data->{$key} = $val;
			}
			return $data;
		}
		return false;
	}

	function num_rows($res)
	{
		// var_dump($res);die();
		if (empty($res) && is_resource($this->res)){
			$res = $this->res;
		}
		if (empty($res)){
			return false;
		}
		$return = mysql_num_rows($res);
		if (! $return){
			if ($return === 0){
				return $return;
			}
			elseif ($return > 1){
				return $return;
			}
			else if ($return == 1){
				return $return;
			}
			else{
				$return = 'SQL ERROR:' . mysql_error($this->link);
				$this->errors[] = $return;
				return false;
			}
		}
		
		return $return;
	}

	function select($what, $escape = true)
	{
		$this->what = $what;
		return $this;
	}

	function from($table)
	{
		$this->table = $table;
		return $this;
	}

	function getall()
	{}

	function where($key, $value, $escape = true)
	{
		if (empty($key) || empty($value)){
			$this->error(
					'empty value sent to $this->where(), query will abort :-(');
		}
		if (stristr($key, '!=') || stristr($key, '>') || stristr($key, '<')){
			$strs = explode(' ', $key);
			$key = $strs[0];
			$operator = $strs[1];
		}
		else{
			$operator = ' = ';
		}
		if (! isset($this->where[$key])){
			$this->where[$key] = new stdClass();
		}
		
		if ($escape){
			// $key = mysql_real_escape_string( $key );
			$value = mysql_real_escape_string($value);
			$this->where[$key]->field = '`' . $key . '`';
			$this->where[$key]->value = '"' . $value . '"';
			$this->where[$key]->operator = $operator;
		}
		else{
			$this->where[$key]->field = $key;
			$this->where[$key]->value = $value;
			$this->where[$key]->operator = $operator;
		}
		return $this;
	}
	
	function where_not($key, $value, $escape = true)
	{
		if (empty($key) || empty($value)){
			$this->error(
					'empty value sent to $this->where(), query will abort :-(');
		}
	
		if (stristr($key, '!=') || stristr($key, '>') || stristr($key, '<')){
			$strs = explode(' ', $key);
			$key = $strs[0];
			$operator = $strs[1];
		}
		else{
			$operator = ' != ';
		}
		if (! isset($this->where[$key])){
			$this->where[$key] = new stdClass();
		}
	
		if ($escape){
			// $key = mysql_real_escape_string( $key );
			$value = mysql_real_escape_string($value);
			$this->where[$key]->field = '`' . $key . '`';
			$this->where[$key]->value = '"' . $value . '"';
			$this->where[$key]->operator = $operator;
		}
		else{
			$this->where[$key]->field = $key;
			$this->where[$key]->value = $value;
			$this->where[$key]->operator = $operator;
		}
		return $this;
	}

	function where_like($key, $value, $escape = true)
	{
		if (empty($key) || empty($value)){
			$this->error(
					'empty value sent to $this->where(), query will abort :-(');
		}
		if (! isset($this->where_like[$key])){
			$this->where_like[$key] = new stdClass();
		}
		if ($escape){
			// $key = mysql_real_escape_string( $key );
			$value = mysql_real_escape_string($value);
			$this->where_like[$key]->field = '`' . $key . '`';
			$this->where_like[$key]->value = '"' . $value . '"';
		}
		else{
			$this->where_like[$key]->field = $key;
			$this->where_like[$key]->value = $value;
		}
		return $this;
	}

	function in()
	{}

	function where_or($data = array())
	{
		
	}

	function last_query($stop = false)
	{
		if ($stop){
			echo 'Last Query: "' . $this->last_sql . '"';
			die();
		}
		return $this->last_sql;
	}

	function where_array(array $p_a_where = array(), $escape = true)
	{
		foreach ($p_a_where as $key => $value){
			
			$this->where($key, $value, $escape);
		}
		
		return $this;
	}

	function where_like_array(array $p_a_where_like = array(), $escape = true)
	{
		foreach ($p_a_where_like as $key => $value){
			
			$this->where_like($key, $value, $escape);
		}
		
		return $this;
	}

	private function where_single()
	{}

	private function obj($array = array())
	{
		return (object) $array;
	}

	private function arr($object)
	{
		return (array) $object;
	}

	private function error($error = 'error accured')
	{
		$this->errors[] = $error . "<br />\nMySql Error:".mysql_error()."<br />\n";
		return;
	}
}
?>