Location: PHPKode > scripts > CRUDités > crudit/class.crudites.php
<?php
/**
 * CRUDités - ezSQL - MySQL utility wrapper
 * 
 * CRUDités is an extension of the great and well known {@link http://www.woyano.com/jv/ezsql ezSQL class}.
 * It's expecially written for MySQL Database. 
 * Depends on ezSQL_core and ezSQL_mysql
 * @package CRUDites
 * @author Marco "DWJ" Solazzi <hide@address.com> 
 * @link http://www.dwightjack.com>
 * @version 0.2b
 * @copyright Copyright &copy; 2008-2009, Marco Solazzi
 * @license Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL (http://www.opensource.org/licenses/gpl-2.0.php) licenses.
 */

class CRUDites extends ezSQL_mysql {

	/**
	 * @var mixed Tables prefix
	 */
	protected $dbprefix = false;
	
	/**
	 * @var string Placeholder to use in queries if database prefix is used
	 * @access protected 
	 */
	protected $dbprefix_placeholder = "#__";
	
	/**
	 * @var mixed Table to which queries are bound
	 * @access protected
	 */
	protected $table_bind = false;
	
	/**
	 * @var array Array of bindable tables
	 * @access protected 
	 */
	protected $tables = array();
	
	/**
	 * @var array Array listing fields' names of current bound table
	 * @access protected
	 */
	protected $current_table = null;
	
	/**
	 * @var string Primary key for current bound table, if exists
	 * @access protected
	 */
	protected $current_primary = null;
	
	/**
	 * @var array Utility options like date format
	 * @access protected
	 */
	protected $options = array(
		'date_locale' => '%d/%m/%Y',
		'time_locale' => '%H:%M:%S',
		'datetime_locale' => '%d/%m/%Y %H:%M:%S'
	);
	//private $server = array();
	
	/**
	* Constructor function
	* 
	* @param string $dbuser Database username
	* @param string $dbpassword Database password
	* @param string $dbname Database name
	* @param string $dbhost (Optional) Database host, defaults to localhost
	* @param string $prefix (Optional) Tables' prefix, defaults to none
	*/
	function __construct ($dbuser='', $dbpassword='', $dbname='', $dbhost='localhost',$prefix=false)
	{
		parent::ezSQL_mysql($dbuser, $dbpassword, $dbname, $dbhost);
		/*foreach($_SERVER as $key => $value) {
			$this->server[$key] = $value;
		}*/
		$this->datetime_locale = $this->date_locale.' '.$this->time_locale;
		$this->dbprefix = $prefix;
	}
	
	/*
	 * GENERAL UTILITY METHODS
	 */
	
	/**
	 * Converts an array to a string with parameters, by combining keys and values.
	 * Values which are arrays may be imploded as a comma separated string
	 * 
	 * Inspired by Joomla 1.5 Framework
	 * @param array $array Input array
	 * @param string $innerglue (Optional) String to place between each key and value. Defaults to "="
	 * @param string $outerglue (Optional) String to place between each key/value pair. Defaults to " AND "
	 * @param bool $recurse (Optional) If set to true it will implode array values which are arrays in a comma separated string. Defaults to true
	 * @return string 
	 */
	function array_to_string( $array = null, $inner_glue = '=', $outer_glue = ' AND ',$recurse=true)
	{
		$output = array();

		if (is_array($array))
		{
			foreach ($array as $key => $item)
			{
				if (is_array ($item) && $recurse)
				{
					$output[] = "{$key} IN (".$this->implode(",",$item).") ";
				}
				else {
					$output[] = " {$key} {$inner_glue} ".$this->check_quotes($item)." ";
				}
			}
		}

		return implode( $outer_glue, $output);
	}
	
	/**
	 * Checks if a string is correctly escaped and quoted for SQL queries
	 * 
	 * @param mixed $var A variable to check
	 * @return mixed
	 */
	protected function check_quotes($var) {
		if (is_string($var)) {
			$var = "'".$this->escape($var)."'";
		}
		return $var;
	} 
	
	/**
	 * String safe version of PHP implode function
	 * 
	 * @see check_quotes()
	 * @param string $glue String to use to join array elements
	 * @param array $array Input array
	 * @return string
	 */
	function implode ($glue,$array) {
		if (is_array($array) && !empty($glue)) {
			$quoted_array = array_map(array($this,'check_quotes'),$array);
			return implode($glue,$quoted_array);
		}
	}
	
	/**
	 * Returns current date and time in a MySQL DATE formatted string (yyyy-mm-dd 00:00:00)
	 * 
	 * @return string
	 */
	function mysql_now () {
		return date('Y-m-d H:m:s');
	}
	
	/**
	 * Returns current date in a MySQL DATE formatted string (yyyy-mm-dd)
	 * 
	 * @return string
	 */
	function mysql_curdate () {
		return date('Y-m-d');
	}
	
	/**
	 * Formats a formatted date or datetime to MySQL date or datetime
	 * 
	 * @param string $string String to format
	 * @param string $input Input format. May be a default locale (date,time or datetime) or a strptime allowed format {@link http://us2.php.net/manual/en/function.strptime.php strptime}
	 * @param string $output MySQL output format. May be mysql_date, mysql_time, mysql_datetime or any date allowed format {@link http://us2.php.net/manual/en/function.date.php date}
	 * 
	 * @return string 
	 */
	function mysql_date_format($string=null,$input=null,$output=null) {
		$return = null;
		if ((bool)$input && (bool)$output ) {
			if ($this->get_option($input.'_locale') != null) {
						$input_format = $this->get_option($input.'_locale');
			} else {
				$input_format = $input;
			}
			$date_array = strptime($string, $input_format);
			$timestamp = $this->strptime_to_timestamp($date_array);
			
			switch ($output) {
				case 'mysql_datetime':
					$format = 'Y-m-d H:m:s';
				break;
				case 'mysql_date':
					$format = 'Y-m-d';
				break;
				case 'mysql_time':
					$format = 'H:m:s';
				break;
				default:
					$format = $output;
				break;	
			}
		}
		return date($format,$timestamp);
	}
	
	/**
	 * Converts a passed in date/time string to timestamp
	 * 
	 * @param string $string Input string
	 * @param string $format Input string format. May be a default locale (date,time or datetime) or a strptime allowed format {@link http://us2.php.net/manual/en/function.strptime.php strptime}
	 * @see mysql_date_format()
	 * @return string 
	 */
	function to_timestamp ($string,$format) {
		return $this->mysql_date_format($string,$format,'U');
	}
	
	/**
	 * Converts and array generated by strptime to a timestamp
	 * 
	 * @access protected
	 * @param array $array (Optional) Input array, if none is pass current timestamp will be returned
	 * @return string
	 */
	protected function strptime_to_timestamp ($array=null) {
		if (is_array($array)) {
		return mktime( 
			intval($array['tm_hour']), 
			intval($array['tm_min']), 
			intval($array['tm_sec']), 
			intval($array['tm_mon'])+1,
			intval($array['tm_mday']),
			intval($array['tm_year'])+1900
			);
		} else {
			return time();
		}
	}
	
	/**
	 * Takes a multidimensional array and returns an array with one value as key and another as value
	 * 
	 * Example:
	 * <code>
	 * $inputArray = array(
	 * 		0 => array('one','two','three'),
	 * 		1 => array('four','five','six')
	 * );
	 * $flatArray = $db->flat_array($inputArray);
	 * print_r($flatArray);
	 * Array (
	 * 	'one'  => 'two',
	 * 	'four' => 'five'
	 * )
	 * </code>
	 * @param array $array Input Array
	 * @param mixed $key1 (Optional) Key of elements to use as keys. Defaults to 0
	 * @param mixed $key2 (Optional) Key of elements to use as values. Defaults to 1
	 * @return array
	 */
	function flat_array ($array,$key1=0,$key2=1) {
		$newA = array();
		foreach ($array as $pair) {
			$newA[$pair[$key1]] = $pair[$key2];
		}
		return $newA;
	}
	
	/*
	 * OPTIONS METHODS
	 */
	
	/**
	 * Gets an option value
	 * 
	 * @param string $var Option name
	 * @see $option
	 * @return mixed Option value or null
	 */
	function get_option ($var) {
		return array_key_exists($var,$this->options) ? $this->options[$var] : null;
	}
	
	/**
	 * Sets an option
	 * 
	 * @param string $var Option name
	 * @param string $value Value of the option
	 */
	function set_option ($var,$value) {
		if (array_key_exists($var,$this->options)) {
			$this->options[$var] = $value;
		}
	}
	
	/**
	 * Gets a table name by applying prefix placeholder (#__) subsitution if needed
	 * 
	 * @access protected
	 * @param string $table Table name
	 * @return string
	 */
	protected function table_name ($table='') {
		return $this->dbprefix === false ? $table : str_replace($this->dbprefix_placeholder,$this->dbprefix,$table);
	}
	
	/*
	 * QUERY BUILDING METHODS
	 */
	
	/**
	 * Returns a select query with options
	 * 
	 * Example:
	 * <code>
	 * Available statements (could be in random order)
	 * $query1 = $db->select_query(array(
	 * 		'select' => 'id,name,surname',
	 * 		'from' => 'customer_names',
	 * 		'where' => 'id >= 1'
	 * ));
	 * 
	 * $query2 = $db->select_query(array(
	 * 		'select' => 'id,surname',
	 * 		'from' => 'customer_names',
	 * 		'where' => array('name'=>'Bob','city' => 'London'),
	 * 		'order' => 'name ASC,id ASC ',
	 * 		'limit' => 2 //just two rows
	 * ));
	 * 
	 * If select statement is not specified all columns will be retrieved
	 * </code> 
	 * @param array $array An array containing required statements
	 * @return string
	 */
	function select_query($array=array()) {
		$array = array_merge(array('select'=>'*'),$array);
		$query = "";
		if (!array_key_exists('from',$array) && !$this->table_bind) {
			return $query;
		} else {
			$table = array_key_exists('from',$array) && (bool)($array['from']) ? $this->table_name($array['from']) : $this->table_bind; 
			$query = "SELECT ".$array['select']." FROM ".$table;
		}
		if (array_key_exists('where',$array) && !empty($array['where'])) {
			$query .= " WHERE ".(is_array($array['where']) ? $this->array_to_string($array['where']) : strval($array['where']));
		}
		if (array_key_exists('order',$array)) {
			$query .= " ORDER BY ".$array['order'];
		}
		if (array_key_exists('limit',$array)) {
			$query .= " LIMIT ".( is_array($array['limit']) ? implode(',',$array['limit']) : $array['limit'] );
		}
		return $query;
	}
	
	/**
	 * Returns an insert query
	 * 
	 * @param string $table Table name
	 * @param array $value_array An array where keys are table fields' names and values are fields' values to store
	 * @param bool $compat (Optional) Uses a compatibility routine with old versions of CRUDites
	 * @return string 
	 */
	function insert_query ($table,$value_array,$compat=false)
	{
		$keys = "";
		$values = "";
		foreach ($value_array as $key=>$value) 
		{
			if ((bool)$value) {
				$keys .= $key . ",";
				/**
				 * see if array value is a MySQL function (ie NOW(), CURDATE(), ...) only for compatibility
				 */
				if ($compat) {
					$values .= is_string($value) && preg_match("/\(.*\)/",$value) != 1 ? "'" . trim($this->escape($value)) . "'," : $value.",";
				} else {
					if (is_string($value)) {
						$value = trim($value);
					}
					$values .= $this->check_quotes($value).",";
				}
			}
		}
		$keys = substr($keys, 0, -1);
		$values = substr($values, 0, -1);
		$query = "INSERT INTO ".$this->table_name($table)." (".$keys.") VALUES (".$values.")";
		return $query;
	}
	
	/**
	 * Returns an update query
	 * 
	 * @param string $table Table name
	 * @param array $value_array An array where keys are table fields' names and values are fields' values to update
	 * @param mixed $where Conditional string or array  ('fieldname'=>'fieldvalue') to define rows to be updated 
	 * @param bool $all (Optional) Uses a compatibility routine with old versions of CRUDites 
	 * @param bool $compat (Optional) Uses a compatibility routine with old versions of CRUDites
	 * @return string 
	 */
	function update_query ($table,$value_array,$where,$all=false,$compat=false)
	{
		$list = "";
		foreach ($value_array as $key=>$value) 
		{
			if ($compat && ($value == 0 || $value !="" || $all)) {
				if (is_string($value) && preg_match("/\(.*\)/",$value) != 1 ) {
					$value = "'" . trim($value) . "'";
				}
				$list .= "{$key}={$value},";
			}
			
			
		}
		if (!empty($list)) {
			$list = substr($list, 0, -1);
		}
		if (!$compat) {
			$list = $this->array_to_string($value_array,'=',',',false);
		}
		$where = " WHERE ".(is_array($where) ? $this->array_to_string($where) : strval($where));
		$query = "UPDATE ".$this->table_name($table)." SET {$list} {$where}";
		return $query;
		
	}

	/**
	 * Returns either an update or insert query based on param $type
	 * 
	 * @param string $table Table name
	 * @param array $value_array An array where keys are table fields' names and values are fields' values to update
	 * @param string $type Type of query. Allowed values are update or insert
	 * @param mixed $where (Not needed if type is insert) Conditional string or array  ('fieldname'=>'fieldvalue') to define rows to be updated 
	 * @param bool $all (Optional. Not needed if type is insert) Uses a compatibility routine with old versions of CRUDites 
	 * @param bool $compat (Optional) Uses a compatibility routine with old versions of CRUDites
	 * @return string 
	 */
	function build_query ($table,$value_array,$type,$where,$compat=false) {
		switch ($type) {
			case "update":
				$query = $this->update_query($table,$value_array,$where,true,$compat);
			break;
			case "insert":
				$query = $this->insert_query($table,$value_array,$compat);
			break;
		}
		return $query;
	}
	
	/**
	 * DATABASE QUERY METHODS
	 */

	/**
	 * Submits passed in query string to the database
	 * 
	 * @param string $query Query to submit
	 * @param bool $isupdate (Optional) Set this parameter to true if query is an update query. Defaults to false
	 * @return bool Returns true if query succeeded else false
	 */
	function send_query ($query,$isupdate=false)
	{
		$query = $this->table_name($query);
		if ( $this->query ($query) || ($isupdate && $this->rows_affected == 0))
		{
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * Returns an array of database rows, either in object or array format
	 * 
	 * @param array $queryArray An array containing required statements
	 * @param constant $output (Optional) Type of rows in the list. May be OBJECT,ARRAY_N (array with numeric index) or ARRAY_A (associative array). Defaults to OBJECT
	 * @see select_query()
	 * @see get_results()
	 * @return array|bool Returns an array with database rows or false on no results
	 */		
	function get_data ($queryArray=array(),$output=OBJECT) {
		if (count($queryArray) == 0) {
			return false;
		} else {
			$query = $this->select_query($queryArray);
			$results = $this->get_results($query,$output);
			return count($results) > 0 ? $results : false;
		}
	}
	
	/**
	 * Returns an array with all rows and colums from a give table
	 * 
	 * @param string $table Table to use
	 * @param constant $output (Optional) Type of rows in the list. May be OBJECT,ARRAY_N (array with numeric index) or ARRAY_A (associative array). Defaults to OBJECT
	 * @see get_data()
	 * @return array|bool Returns an array with database rows or false on no results
	 */
	function get_table ($table=null,$output=OBJECT) {
		return $this->get_data(array('from'=>$table),$output);
	}
	
	/**
	 * Returns an array of database rows 
	 * 
	 * Example: 
	 * <code>
	 * $results = $db->get_where("name","my_table","surname='Doe'");
	 * //will output an array of objects
	 * //to get all columns use this syntax
	 * $results = $db->get_where("my_table","surname='Doe'");
	 * </code>
	 * Works like get_data() but accepts a variable number of strin arguments
	 * @param mixed $string[, $string2...] Select statements. May be what to select, from which table and where, or just from which table and where. An additional last argument may be the output format
	 * @see get_data
	 * @return array|bool Returns an array with database rows or false on no results
	 */
	function get_where () {
		$numargs = func_num_args();
		$args = func_get_args(); //cols,table,where,output
		$queryArray = array();
		
		//cols,table,where[, output]
		if ($numargs > 2 && is_array($args[$numargs-2])) { //some table columns are required
			$queryArray['select'] = $args[0];
			$queryArray['from'] = $args[1];
			$queryArray['where'] = $args[2];
			$output = $numargs > 3 ? $args[3] : OBJECT;
		} else { //get all columns that apply
			$queryArray['from'] = $args[0];
			$queryArray['where'] = $args[1];
			$output = $numargs > 2 ? $args[2] : OBJECT;
		}
		return $this->get_data($queryArray,$output);
	} 
	
	/**
	 * Returns an array with two given database columns as array keys and values
	 *
	 * Example: 
	 * <code>
	 * $results = $db->get_pair("my_table","id","name","surname='Doe'")
	 * print_r($results);
	 * 
	 * Array (
	 * 		1 => 'John',
	 * 		2 => 'Jack',
	 * 		4 => ...
	 * )
	 * </code>
	 * @param string $table Table name
	 * @param string $key1 Column name to use as key in the resulting array
	 * @param string $key2 Column name to use as value in the resulting array
	 * @param string $where (Optional) Condition to filter results
	 * @see get_where()
	 * @see flat_array()
	 * @return array
	 */
	function get_pair ($table,$key1,$key2,$where="") {
		$results = $this->get_where($key1.",".$key2,$table,$where);
		return $this->flat_array($results,$key1,$key2);
	}
		
	/**
	 * Counts number of rows with optional where statement
	 * 
	 * @param string $table Table name
	 * @param string|array $where (Optional) Where statement
	 * @see select_query()
	 * @return int
	 */
	function count_rows($table=null,$where='') {
		$query = $this->select_query(array('select'=>'COUNT(*)','from'=>$table,'where'=>$where));
		return $this->get_var($query);
	}
	 
	/**
	 * Returns true or number of occurrence of a row if it exists
	 * 
	 * @param string $table Table name
	 * @param string|array $field Field to use for search or array with field => fieldvalue
	 * @param string $value (Optional) Value to search for if $field is a string
	 * @param string $return (Optional) If set to true will return the number of occurrence of the searched values, else will return just true (defaults to false)
	 * @see count_rows()
	 * @return bool|int
	 */
	function row_exists ($table=null,$field,$value="",$return=false)
	{
		if (is_string($field) && empty($value)) {
			return false;
		}
		if (is_array($field)) {
			$where = $field;
		} else {
			$where = array();
			$where[$field] =  $value;
		}
		if ($rows = $this->count_rows($table,$where)) {
			return $return ? true : $rows;
		}
	}

	/**
	 * Inserts a row in the table only if there's no other row with passed in column value
	 * 
	 * @param string $table Table name
	 * @param string|array $field Field to use for search or array with field => fieldvalue
	 * @param string $value (Optional) Value to search for if $field is a string
	 * @param string $query Insert query
	 * @see row_exists()
	 * @return bool True on query success
	 */		
	function insert_unique_to ($table,$field,$value,$query)
	{
		if ( !$this->row_exists($table,$field,$value) )	{
			return $this->send_query($query);
		} else {
			return false;
		}
	}
	
	/**
	 * Deletes a row from passed in table
	 * 
	 * @param string $table Table name
	 * @param string|array $where (Optional) Where statement as string or as an array of field => fieldvalue
	 * @return bool True when row is successfully deleted
	 */
	function delete_from ($table,$where='') {
		if (!empty($where)) {
			$where = "WHERE ".(is_array($where) ? $this->array_to_string($where) : strval($where));
		}
		$query = "DELETE FROM ".$this->table_name($table)." {$where}";
		$this->query($query);
		return (bool)($this->rows_affected > 0);
	}	
	
	/**
	 * Gets a single value from a single row from a table
	 * 
	 * @param string $table Table name
	 * @param string $field Field to return
	 * @param string|array $where (Optional) Where statement as string or as an array of field => fieldvalue
	 * @return mixed
	 */
	function get_value ($table=null,$field,$where=null) {
		if (!(bool)$table) {
			return false;
		}
		$query = $this->select_query(array('select'=>$field,'from'=>$table,'where'=>$where)); 
		return $this->get_var($query);
	}
	
	/**
	 * Sets value of a single field in a table
	 * 
	 * @param string $table Table name
	 * @param string $field Field to return
	 * @param string $value Value to set
	 * @param string|array $where (Optional) Where statement as string or as an array of field => fieldvalue
	 * @return bool True on query success
	 */
	function set_value ($table=null,$field,$value,$where=null) {
		if (!(bool)$table) {
			return false;
		}
		$query = $this->update_query ($table,array("".$field=>$value),$where);
		return $this->send_query($query);
	}
	
	/**
	 * Returns an array of values from a single column
	 * 
	 * @param string $table Table name
	 * @param string $field Table column to return
	 * @return array|bool An array of values or false on error
	 */
	function get_col_values( $table=null , $field ){
		
		$table = empty($table) ? $this->table_bind : $this->table_name($table);
		if (!(bool)$table) {
			return false;
		}
		$query = "SHOW COLUMNS FROM `$table` LIKE '$field'";
		$row = $this->get_row($query,ARRAY_N);
		if (count($row) > 0) {
			$regex = "/'(.*?)'/";
			preg_match_all( $regex , $row[1], $enum_array );
			$enum_fields = $enum_array[1];
			return $enum_fields;
		}
			return false;
		}

	/*
	 * TABLE BINDING METHODS
	 */
	
	/**
	 * Adds a table to the internal table reference
	 * 
	 * Example:
	 * <code>
	 * $db->add_table(
	 * 		'#__my_table',
	 * 		array(
	 * 			'id',
	 * 			'name',
	 * 			'surname'
	 * 		)
	 * );
	 * </code> 
	 * @param string $table Table name (with or without prefix)
	 * @param array $fields An array containing all table fields
	 * @param string $primary (Optional) Table primary key (defaults to 'id')
	 * @param bool $override (Optional) If set to true any already added table with the same name will be overwritten. Defaults to false
	 */
	function add_table ($table,$fields=null,$primary='id',$override=false) {
		if (is_array($fields) && ( !array_key_exists($table,$this->tables) || $override === true ) ) {
			if ((bool)$primary) {
				$fields = array_merge($fields,array('__primary'=>$primary));
			}
			$this->tables[$table] = $fields;
		}
	}
	
	/**
	 * Same as add_table(), but accepts as first arguments a multidimensional associative array with tables' names as keys and field array as value.
	 * Primary key can be marked inside the field array as a associative key __primary => 'fieldname'
	 * 
	 * Example:
	 * <code>
	 * $db->add_tables(array(
	 * 		'#__my_table' => array (
	 * 			'id',
	 * 			'name',
	 * 			'surname',
	 * 			'__primary' => 'id'
	 * 		),
	 * 		'#__my_second_table' => array (
	 * 			[...]
	 * 		)
	 * ));
	 * </code>
	 * @param array $array The multidimensional associative array of tables to insert
	 * @param bool $override (Optional) If set to true any already added table with the same name will be overwritten. Defaults to false.
	 * @see add_table()
	 */
	function add_tables ($array=array(),$override=false) {
		if (!is_array($array)) {
			return false;
		}
		foreach ($array as $table => $fields) {
			$this->add_table($table,$fields,null,$override);
		}
	}
	
	/**
	 * Selects a table from the internal table reference stored to be use with binding methods, if it exists
	 * 
	 * Example:
	 * <code>
	 * $db->bind('#__my_table');
	 * </code> 
	 * @param strin $table Name of selected table
	 */
	function bind ($table) {
		if (array_key_exists($table,$this->tables)) {
			$this->current_table = $this->tables[$table];
			$this->current_primary = $this->current_table['__primary'];
			//unset($this->current_table['__primary']); TODO: add type description to tables
			$this->table_bind = $this->table_name($table); 	
		}
	}
	
	/**
	 * Returns an array of database rows from bound table
	 * 
	 * If no params are passed in all rows from the bound table are returned as an array of objects
	 * @param array $array (Optional) An array containing select statements
	 * @param constant $output (Optional) Type of rows in the list. May be OBJECT,ARRAY_N (array with numeric index) or ARRAY_A (associative array). Defaults to OBJECT 
	 * @see get_data()
	 * 
	 * @return array|bool Returns an array with database rows or false on no results
	 */
	function select_rows ($array=array(),$output=OBJECT) {
		$queryArray = array_merge(array('from'=>$this->table_bind),$array);
		return $this->get_data ($queryArray,$output);
	}
	
	/**
	 * Counts the number of rows from bound table
	 * 
	 * @param string|array $where (Optional) where statement
	 * @see count_rows()
	 * @return int Number of rows
	 */
	function count ($where='') {
		return $this->count_rows($this->table_bind,$where);
	}
	
	/**
	 * Returns true or number of occurrence of a row if it exists
	 * 
	 * @param string $val Value to search for
	 * @param string $col (Optional) Field to use for search. Defaults to primary key of bound table
	 * @param string $return (Optional) If set to true will return the number of occurrence of the searched values, else will return just true (defaults to false)
	 * @return bool|int
	 */
	function exists ($val='',$col=null,$return=false) {
		//if (empty($col) || !array_key_exists($col,$this->current_table)) {TODO:see type description above
		if (empty($col) || !in_array($col,$this->current_table)) {
			$col = $this->current_primary;
		}
		return $this->row_exists ($this->table_bind,$col,$val,$return);
	}
	
	/**
	 * Returns an array with two given table columns as array keys and values
	 * 
	 * @param string $key1 Column name to use as key in the resulting array
	 * @param string $key2 Column name to use as value in the resulting array
	 * @param string $where (Optional) Condition to filter results
	 * @see get_pair()
	 * @return array
	 */
	function pair ($key1,$key2,$where="") {
		return $this->get_pair ($this->table_bind,$key1,$key2,$where);
	}
	
	/**
	 * Inserts a row in the bound table only if there's no other row with passed in value in current primary key
	 * 
	 * @param string $value Value to search for in primary key
	 * @param string $query Insert query
	 * @return bool True on query success
	 */			
	function insert_unique ($value,$query) {
		if(is_array($query)) {
			//TODO
		}
		return $this->insert_unique_to ($this->table_bind,$this->current_primary,$value,$query);
	}

	/**
	 * Deletes a row from bound table
	 * 
	 * @param string $table Table name
	 * @param string|array $where (Optional) Where statement as string or as an array of field => fieldvalue
	 * @return bool True when row is successfully deleted
	 */	
	function delete ($where='',$col=null) {
		if (is_int($where)) {
			$where = $this->current_primary.'='.$where;
		}
		return $this->delete_from ($this->table_bind,$where);
	}
	
	/**
	 * Stores data in the bound table, either inserting a new row or updateing an existing one.
	 * 
	 * If in passed in data array is present a key with same name as the current primary key, row is updated, else a new row will be stored
	 * 
	 * Example:
	 * <code>
	 * // add a new table and bind the object to it 
	 * $db->add_table('#__my_table',
	 * 		array(
	 * 			'id',
	 * 			'name'
	 * 		),
	 * 		'id' //id is the primary key
	 * );
	 * $db->bind('#__my_table');
	 * 
	 * // adds a new row
	 * $new_row = array('name'=>'John');
	 * $db->store($new_row); 
	 * 
	 * // update a row
	 * $new_row = array('id'=>2,'name'=>'Mark');
	 * $db->store($new_row); 
	 * </code>
	 * 
	 * @param array $value_array An array containing fields as keys and fields value as values
	 * @return bool True if query is successful, else false
	 */
	function store ($value_array) {
		
		// check if array's keys passed in are present in current table
		$table_fields = array_flip($this->current_table);
		$valid_values = array_intersect_key($value_array,$table_fields);
		
		//store query type
		if (array_key_exists($this->current_primary,$valid_values)) {
			$type = 'update';
			$update=true;
			$id = $valid_values[$this->current_primary];
			unset($valid_values[$this->current_primary]);
		} else {
			$update=false;
			$type='insert';
		}
		
		$query = $this->build_query($this->table_bind,$valid_values,$type,$this->current_primary.'='.$id);
		return $this->send_query($query,$update);
	}
		
	/*
	 * COMPATIBILITY METHODS
	 * This methods are deprecated and mantained only for compatibility reasons to ensure
	 * correct functionality with old versions (<0.2) of CRUDités.
	 */
	
	/**
	 * @see get_where()
	 * @deprecated 0.2b - 03/lug/2009
	 */
	function getWhere ($what,$table,$where=false) {
		return $this->get_where($what,$table,$where,ARRAY_A);
	}
	
	/**
	 * @see get_where()
	 * @deprecated 0.2b - 03/lug/2009
	 */
	function getObjWhere ($what,$table,$where=false) {
		return $this->get_where($what,$table,$where);
	}

	/**
	 * @see array_to_string()
	 * @deprecated 0.2b - 03/lug/2009
	 */	
	function arrayToString( $array = null, $inner_glue = '=', $outer_glue = ' AND ') {
		return $this->array_to_string( $array, $inner_glue, $outer_glue);
	}
	
	/**
	 * @see row_exists()
	 * @deprecated 0.2b - 03/lug/2009
	 */		
	function checkTable ($table,$field,$value="",$return=false) {
		return $this->row_exists($table,$field,$value,$return);
	}

	/**
	 * @see send_query()
	 * @deprecated 0.2b - 03/lug/2009
	 */		
	function sendQuery ($query,$isupdate=false) {
		return $this->send_query($query,$isupdate);
	}
	
	/**
	 * @see query_insert()
	 * @deprecated 0.2b - 03/lug/2009
	 */
	function insertQuery ($table,$valueArray) {
		return $this->query_insert($table,$valueArray,true);
	}

	/**
	 * @see update_query()
	 * @deprecated 0.2b - 03/lug/2009
	 */
	function updateQuery ($table,$valueArray,$col,$val,$all=false) {
		return $this->update_query ($table,$valueArray,"{$col} = {$val}",$all,true);
	}
	
	/**
	 * @see insert_unique_to()
	 * @deprecated 0.2b - 03/lug/2009
	 */
	function insertAgainst ($table,$field,$value,$query) {
		return $this->insert_unique_to($table,$field,$value,$query);
	}

	/**
	 * @see build_query()
	 * @deprecated 0.2b - 03/lug/2009
	 */
	function buildQuery ($table,$type="insert",$col=null,$val=null) {
		return $this->build_query ($table,$type,"{$col} = {$val}",true);
	}

	/**
	 * @see delete_from()
	 * @deprecated 0.2b - 03/lug/2009
	 */
	function deleteRow ($table,$where) {
		return $this->delete_from($table,$where);
	}

	/**
	 * @see get_pair()
	 * @deprecated 0.2b - 03/lug/2009
	 */
	function getPair ($table,$key1,$key2,$where="") {
			return $this->get_pair($table,$key1,$key2,$where);
	}

	/**
	 * @see flat_array()
	 * @deprecated 0.2b - 03/lug/2009
	 */
	function flatArray ($array,$key1=0,$key2=1) {
		return $this->flat_array ($array,$key1,$key2);
	}
}
?>
Return current item: CRUDités