Source for file class.crudites.php

Documentation is available at class.crudites.php

  1. <?php
  2. /**
  3.  * CRUDités - ezSQL - MySQL utility wrapper
  4.  * 
  5.  * CRUDités is an extension of the great and well known {@link http://www.woyano.com/jv/ezsql ezSQL class}.
  6.  * It's expecially written for MySQL Database.
  7.  * Depends on ezSQL_core and ezSQL_mysql
  8.  * @package CRUDites
  9.  * @author Marco "DWJ" Solazzi <hello@dwightjack.com>
  10.  * @link http://www.dwightjack.com>
  11.  * @version 0.2b
  12.  * @copyright Copyright &copy; 2008-2009, Marco Solazzi
  13.  * @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.
  14.  */
  15.  
  16. class CRUDites extends ezSQL_mysql {
  17.  
  18.     /**
  19.      * @var mixed Tables prefix
  20.      */
  21.     protected $dbprefix = false;
  22.     
  23.     /**
  24.      * @var string Placeholder to use in queries if database prefix is used
  25.      * @access protected
  26.      */
  27.     protected $dbprefix_placeholder = "#__";
  28.     
  29.     /**
  30.      * @var mixed Table to which queries are bound
  31.      * @access protected
  32.      */
  33.     protected $table_bind = false;
  34.     
  35.     /**
  36.      * @var array Array of bindable tables
  37.      * @access protected
  38.      */
  39.     protected $tables = array();
  40.     
  41.     /**
  42.      * @var array Array listing fields' names of current bound table
  43.      * @access protected
  44.      */
  45.     protected $current_table = null;
  46.     
  47.     /**
  48.      * @var string Primary key for current bound table, if exists
  49.      * @access protected
  50.      */
  51.     protected $current_primary = null;
  52.     
  53.     /**
  54.      * @var array Utility options like date format
  55.      * @access protected
  56.      */
  57.     protected $options = array(
  58.         'date_locale' => '%d/%m/%Y',
  59.         'time_locale' => '%H:%M:%S',
  60.         'datetime_locale' => '%d/%m/%Y %H:%M:%S'
  61.     );
  62.     //private $server = array();
  63.     
  64.     /**
  65.     * Constructor function
  66.     * 
  67.     * @param string $dbuser Database username
  68.     * @param string $dbpassword Database password
  69.     * @param string $dbname Database name
  70.     * @param string $dbhost (Optional) Database host, defaults to localhost
  71.     * @param string $prefix (Optional) Tables' prefix, defaults to none
  72.     */
  73.     function __construct ($dbuser=''$dbpassword=''$dbname=''$dbhost='localhost',$prefix=false)
  74.     {
  75.         parent::ezSQL_mysql($dbuser$dbpassword$dbname$dbhost);
  76.         /*foreach($_SERVER as $key => $value) {
  77.             $this->server[$key] = $value;
  78.         }*/
  79.         $this->datetime_locale $this->date_locale.' '.$this->time_locale;
  80.         $this->dbprefix = $prefix;
  81.     }
  82.     
  83.     /*
  84.      * GENERAL UTILITY METHODS
  85.      */
  86.     
  87.     /**
  88.      * Converts an array to a string with parameters, by combining keys and values.
  89.      * Values which are arrays may be imploded as a comma separated string
  90.      * 
  91.      * Inspired by Joomla 1.5 Framework
  92.      * @param array $array Input array
  93.      * @param string $innerglue (Optional) String to place between each key and value. Defaults to "="
  94.      * @param string $outerglue (Optional) String to place between each key/value pair. Defaults to " AND "
  95.      * @param bool $recurse (Optional) If set to true it will implode array values which are arrays in a comma separated string. Defaults to true
  96.      * @return string 
  97.      */
  98.     function array_to_string$array null$inner_glue '='$outer_glue ' AND ',$recurse=true)
  99.     {
  100.         $output array();
  101.  
  102.         if (is_array($array))
  103.         {
  104.             foreach ($array as $key => $item)
  105.             {
  106.                 if (is_array ($item&& $recurse)
  107.                 {
  108.                     $output["{$key} IN (".$this->implode(",",$item).") ";
  109.                 }
  110.                 else {
  111.                     $output[" {$key} {$inner_glue} ".$this->check_quotes($item)." ";
  112.                 }
  113.             }
  114.         }
  115.  
  116.         return implode$outer_glue$output);
  117.     }
  118.     
  119.     /**
  120.      * Checks if a string is correctly escaped and quoted for SQL queries
  121.      * 
  122.      * @param mixed $var A variable to check
  123.      * @return mixed 
  124.      */
  125.     protected function check_quotes($var{
  126.         if (is_string($var)) {
  127.             $var "'".$this->escape($var)."'";
  128.         }
  129.         return $var;
  130.     
  131.     
  132.     /**
  133.      * String safe version of PHP implode function
  134.      * 
  135.      * @see check_quotes()
  136.      * @param string $glue String to use to join array elements
  137.      * @param array $array Input array
  138.      * @return string 
  139.      */
  140.     function implode ($glue,$array{
  141.         if (is_array($array&& !empty($glue)) {
  142.             $quoted_array array_map(array($this,'check_quotes'),$array);
  143.             return implode($glue,$quoted_array);
  144.         }
  145.     }
  146.     
  147.     /**
  148.      * Returns current date and time in a MySQL DATE formatted string (yyyy-mm-dd 00:00:00)
  149.      * 
  150.      * @return string 
  151.      */
  152.     function mysql_now ({
  153.         return date('Y-m-d H:i:s');
  154.     }
  155.     
  156.     /**
  157.      * Returns current date in a MySQL DATE formatted string (yyyy-mm-dd)
  158.      * 
  159.      * @return string 
  160.      */
  161.     function mysql_curdate ({
  162.         return date('Y-m-d');
  163.     }
  164.     
  165.     /**
  166.      * Formats a formatted date or datetime to MySQL date or datetime
  167.      * 
  168.      * @param string $string String to format
  169.      * @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}
  170.      * @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}
  171.      * 
  172.      * @return string 
  173.      */
  174.     function mysql_date_format($string=null,$input=null,$output=null{
  175.         $return null;
  176.         if ((bool)$input && (bool)$output {
  177.             if ($this->get_option($input.'_locale'!= null{
  178.                         $input_format $this->get_option($input.'_locale');
  179.             else {
  180.                 $input_format $input;
  181.             }
  182.             $date_array strptime($string$input_format);
  183.             $timestamp $this->strptime_to_timestamp($date_array);
  184.             
  185.             switch ($output{
  186.                 case 'mysql_datetime':
  187.                     $format 'Y-m-d H:m:s';
  188.                 break;
  189.                 case 'mysql_date':
  190.                     $format 'Y-m-d';
  191.                 break;
  192.                 case 'mysql_time':
  193.                     $format 'H:m:s';
  194.                 break;
  195.                 default:
  196.                     $format $output;
  197.                 break;    
  198.             }
  199.         }
  200.         return date($format,$timestamp);
  201.     }
  202.     
  203.     /**
  204.      * Converts a passed in date/time string to timestamp
  205.      * 
  206.      * @param string $string Input string
  207.      * @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}
  208.      * @see mysql_date_format()
  209.      * @return string 
  210.      */
  211.     function to_timestamp ($string,$format{
  212.         return $this->mysql_date_format($string,$format,'U');
  213.     }
  214.     
  215.     /**
  216.      * Converts and array generated by strptime to a timestamp
  217.      * 
  218.      * @access protected
  219.      * @param array $array (Optional) Input array, if none is pass current timestamp will be returned
  220.      * @return string 
  221.      */
  222.     protected function strptime_to_timestamp ($array=null{
  223.         if (is_array($array)) {
  224.         return mktime
  225.             intval($array['tm_hour'])
  226.             intval($array['tm_min'])
  227.             intval($array['tm_sec'])
  228.             intval($array['tm_mon'])+1,
  229.             intval($array['tm_mday']),
  230.             intval($array['tm_year'])+1900
  231.             );
  232.         else {
  233.             return time();
  234.         }
  235.     }
  236.     
  237.     /**
  238.      * Takes a multidimensional array and returns an array with one value as key and another as value
  239.      * 
  240.      * Example:
  241.      * <code>
  242.      * $inputArray = array(
  243.      *         0 => array('one','two','three'),
  244.      *         1 => array('four','five','six')
  245.      * );
  246.      * $flatArray = $db->flat_array($inputArray);
  247.      * print_r($flatArray);
  248.      * Array (
  249.      *     'one'  => 'two',
  250.      *     'four' => 'five'
  251.      * )
  252.      * </code>
  253.      * @param array $array Input Array
  254.      * @param mixed $key1 (Optional) Key of elements to use as keys. Defaults to 0
  255.      * @param mixed $key2 (Optional) Key of elements to use as values. Defaults to 1
  256.      * @return array 
  257.      */
  258.     function flat_array ($array,$key1=0,$key2=1{
  259.         $newA array();
  260.         foreach ($array as $pair{
  261.             $newA[$pair[$key1]] $pair[$key2];
  262.         }
  263.         return $newA;
  264.     }
  265.     
  266.     /*
  267.      * OPTIONS METHODS
  268.      */
  269.     
  270.     /**
  271.      * Gets an option value
  272.      * 
  273.      * @param string $var Option name
  274.      * @see $option
  275.      * @return mixed Option value or null
  276.      */
  277.     function get_option ($var{
  278.         return array_key_exists($var,$this->options$this->options[$varnull;
  279.     }
  280.     
  281.     /**
  282.      * Sets an option
  283.      * 
  284.      * @param string $var Option name
  285.      * @param string $value Value of the option
  286.      */
  287.     function set_option ($var,$value{
  288.         if (array_key_exists($var,$this->options)) {
  289.             $this->options[$var$value;
  290.         }
  291.     }
  292.     
  293.     /**
  294.      * Gets a table name by applying prefix placeholder (#__) subsitution if needed
  295.      * 
  296.      * @access protected
  297.      * @param string $table Table name
  298.      * @return string 
  299.      */
  300.     protected function table_name ($table=''{
  301.         return $this->dbprefix === false $table str_replace($this->dbprefix_placeholder,$this->dbprefix,$table);
  302.     }
  303.     
  304.     /*
  305.      * QUERY BUILDING METHODS
  306.      */
  307.     
  308.     /**
  309.      * Returns a select query with options
  310.      * 
  311.      * Example:
  312.      * <code>
  313.      * Available statements (could be in random order)
  314.      * $query1 = $db->select_query(array(
  315.      *         'select' => 'id,name,surname',
  316.      *         'from' => 'customer_names',
  317.      *         'where' => 'id >= 1'
  318.      * ));
  319.      * 
  320.      * $query2 = $db->select_query(array(
  321.      *         'select' => 'id,surname',
  322.      *         'from' => 'customer_names',
  323.      *         'where' => array('name'=>'Bob','city' => 'London'),
  324.      *         'order' => 'name ASC,id ASC ',
  325.      *         'limit' => 2 //just two rows
  326.      * ));
  327.      * 
  328.      * If select statement is not specified all columns will be retrieved
  329.      * </code>
  330.      * @param array $array An array containing required statements
  331.      * @return string 
  332.      */
  333.     function select_query($array=array()) {
  334.         $array array_merge(array('select'=>'*'),$array);
  335.         $query "";
  336.         if (!array_key_exists('from',$array&& !$this->table_bind{
  337.             return $query;
  338.         else {
  339.             $table array_key_exists('from',$array&& (bool)($array['from']$this->table_name($array['from']$this->table_bind
  340.             $query "SELECT ".$array['select']." FROM ".$table;
  341.         }
  342.         if (array_key_exists('where',$array&& !empty($array['where'])) {
  343.             $query .= " WHERE ".(is_array($array['where']$this->array_to_string($array['where']strval($array['where']));
  344.         }
  345.         if (array_key_exists('order',$array)) {
  346.             $query .= " ORDER BY ".$array['order'];
  347.         }
  348.         if (array_key_exists('limit',$array)) {
  349.             $query .= " LIMIT ".is_array($array['limit']implode(',',$array['limit']$array['limit');
  350.         }
  351.         return $query;
  352.     }
  353.     
  354.     /**
  355.      * Returns an insert query
  356.      * 
  357.      * @param string $table Table name
  358.      * @param array $value_array An array where keys are table fields' names and values are fields' values to store
  359.      * @param bool $compat (Optional) Uses a compatibility routine with old versions of CRUDites
  360.      * @return string 
  361.      */
  362.     function insert_query ($table,$value_array,$compat=false)
  363.     {
  364.         $keys "";
  365.         $values "";
  366.         foreach ($value_array as $key=>$value
  367.         {
  368.             if ((bool)$value{
  369.                 $keys .= $key ",";
  370.                 /**
  371.                  * see if array value is a MySQL function (ie NOW(), CURDATE(), ...) only for compatibility
  372.                  */
  373.                 if ($compat{
  374.                     $values .= is_string($value&& preg_match("/\(.*\)/",$value!= "'" trim($this->escape($value)) "'," $value.",";
  375.                 else {
  376.                     if (is_string($value)) {
  377.                         $value trim($value);
  378.                     }
  379.                     $values .= $this->check_quotes($value).",";
  380.                 }
  381.             }
  382.         }
  383.         $keys substr($keys0-1);
  384.         $values substr($values0-1);
  385.         $query "INSERT INTO ".$this->table_name($table)." (".$keys.") VALUES (".$values.")";
  386.         return $query;
  387.     }
  388.     
  389.     /**
  390.      * Returns an update query
  391.      * 
  392.      * @param string $table Table name
  393.      * @param array $value_array An array where keys are table fields' names and values are fields' values to update
  394.      * @param mixed $where Conditional string or array  ('fieldname'=>'fieldvalue') to define rows to be updated
  395.      * @param bool $all (Optional) Uses a compatibility routine with old versions of CRUDites
  396.      * @param bool $compat (Optional) Uses a compatibility routine with old versions of CRUDites
  397.      * @return string 
  398.      */
  399.     function update_query ($table,$value_array,$where,$all=false,$compat=false)
  400.     {
  401.         $list "";
  402.         foreach ($value_array as $key=>$value
  403.         {
  404.             if ($compat && ($value == || $value !="" || $all)) {
  405.                 if (is_string($value&& preg_match("/\(.*\)/",$value!= {
  406.                     $value "'" trim($value"'";
  407.                 }
  408.                 $list .= "{$key}={$value},";
  409.             }
  410.             
  411.             
  412.         }
  413.         if (!empty($list)) {
  414.             $list substr($list0-1);
  415.         }
  416.         if (!$compat{
  417.             $list $this->array_to_string($value_array,'=',',',false);
  418.         }
  419.         $where " WHERE ".(is_array($where$this->array_to_string($wherestrval($where));
  420.         $query "UPDATE ".$this->table_name($table)." SET {$list} {$where}";
  421.         return $query;
  422.         
  423.     }
  424.  
  425.     /**
  426.      * Returns either an update or insert query based on param $type
  427.      * 
  428.      * @param string $table Table name
  429.      * @param array $value_array An array where keys are table fields' names and values are fields' values to update
  430.      * @param string $type Type of query. Allowed values are update or insert
  431.      * @param mixed $where (Not needed if type is insert) Conditional string or array  ('fieldname'=>'fieldvalue') to define rows to be updated
  432.      * @param bool $all (Optional. Not needed if type is insert) Uses a compatibility routine with old versions of CRUDites
  433.      * @param bool $compat (Optional) Uses a compatibility routine with old versions of CRUDites
  434.      * @return string 
  435.      */
  436.     function build_query ($table,$value_array,$type,$where,$compat=false{
  437.         switch ($type{
  438.             case "update":
  439.                 $query $this->update_query($table,$value_array,$where,true,$compat);
  440.             break;
  441.             case "insert":
  442.                 $query $this->insert_query($table,$value_array,$compat);
  443.             break;
  444.         }
  445.         return $query;
  446.     }
  447.     
  448.     /**
  449.      * DATABASE QUERY METHODS
  450.      */
  451.  
  452.     /**
  453.      * Submits passed in query string to the database
  454.      * 
  455.      * @param string $query Query to submit
  456.      * @param bool $isupdate (Optional) Set this parameter to true if query is an update query. Defaults to false
  457.      * @return bool Returns true if query succeeded else false
  458.      */
  459.     function send_query ($query,$isupdate=false)
  460.     {
  461.         $query $this->table_name($query);
  462.         if $this->query ($query|| ($isupdate && $this->rows_affected == 0))
  463.         {
  464.             return true;
  465.         else {
  466.             return false;
  467.         }
  468.     }
  469.     
  470.     /**
  471.      * Returns an array of database rows, either in object or array format
  472.      * 
  473.      * @param array $queryArray An array containing required statements
  474.      * @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
  475.      * @see select_query()
  476.      * @see get_results()
  477.      * @return array|boolReturns an array with database rows or false on no results
  478.      */        
  479.     function get_data ($queryArray=array(),$output=OBJECT{
  480.         if (count($queryArray== 0{
  481.             return false;
  482.         else {
  483.             $query $this->select_query($queryArray);
  484.             $results $this->get_results($query,$output);
  485.             return count($results$results false;
  486.         }
  487.     }
  488.     
  489.     /**
  490.      * Returns an array with all rows and colums from a give table
  491.      * 
  492.      * @param string $table Table to use
  493.      * @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
  494.      * @see get_data()
  495.      * @return array|boolReturns an array with database rows or false on no results
  496.      */
  497.     function get_table ($table=null,$output=OBJECT{
  498.         return $this->get_data(array('from'=>$table),$output);
  499.     }
  500.     
  501.     /**
  502.      * Returns an array of database rows
  503.      * 
  504.      * Example:
  505.      * <code>
  506.      * $results = $db->get_where("name","my_table","surname='Doe'");
  507.      * //will output an array of objects
  508.      * //to get all columns use this syntax
  509.      * $results = $db->get_where("my_table","surname='Doe'");
  510.      * </code>
  511.      * Works like get_data() but accepts a variable number of strin arguments
  512.      * @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
  513.      * @see get_data
  514.      * @return array|boolReturns an array with database rows or false on no results
  515.      */
  516.     function get_where ({
  517.         $numargs func_num_args();
  518.         $args func_get_args()//cols,table,where,output
  519.         $queryArray array();
  520.         
  521.         //cols,table,where[, output]
  522.         if ($numargs && is_array($args[$numargs-2])) //some table columns are required
  523.             $queryArray['select'$args[0];
  524.             $queryArray['from'$args[1];
  525.             $queryArray['where'$args[2];
  526.             $output $numargs $args[3OBJECT;
  527.         else //get all columns that apply
  528.             $queryArray['from'$args[0];
  529.             $queryArray['where'$args[1];
  530.             $output $numargs $args[2OBJECT;
  531.         }
  532.         return $this->get_data($queryArray,$output);
  533.     
  534.     
  535.     /**
  536.      * Returns an array with two given database columns as array keys and values
  537.      *
  538.      * Example:
  539.      * <code>
  540.      * $results = $db->get_pair("my_table","id","name","surname='Doe'")
  541.      * print_r($results);
  542.      * 
  543.      * Array (
  544.      *         1 => 'John',
  545.      *         2 => 'Jack',
  546.      *         4 => ...
  547.      * )
  548.      * </code>
  549.      * @param string $table Table name
  550.      * @param string $key1 Column name to use as key in the resulting array
  551.      * @param string $key2 Column name to use as value in the resulting array
  552.      * @param string $where (Optional) Condition to filter results
  553.      * @see get_where()
  554.      * @see flat_array()
  555.      * @return array 
  556.      */
  557.     function get_pair ($table,$key1,$key2,$where=""{
  558.         $results $this->get_where($key1.",".$key2,$table,$where);
  559.         return $this->flat_array($results,$key1,$key2);
  560.     }
  561.         
  562.     /**
  563.      * Counts number of rows with optional where statement
  564.      * 
  565.      * @param string $table Table name
  566.      * @param string|array$where (Optional) Where statement
  567.      * @see select_query()
  568.      * @return int 
  569.      */
  570.     function count_rows($table=null,$where=''{
  571.         $query $this->select_query(array('select'=>'COUNT(*)','from'=>$table,'where'=>$where));
  572.         return $this->get_var($query);
  573.     }
  574.      
  575.     /**
  576.      * Returns true or number of occurrence of a row if it exists
  577.      * 
  578.      * @param string $table Table name
  579.      * @param string|array$field Field to use for search or array with field => fieldvalue
  580.      * @param string $value (Optional) Value to search for if $field is a string
  581.      * @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)
  582.      * @see count_rows()
  583.      * @return bool|int
  584.      */
  585.     function row_exists ($table=null,$field,$value="",$return=false)
  586.     {
  587.         if (is_string($field&& empty($value)) {
  588.             return false;
  589.         }
  590.         if (is_array($field)) {
  591.             $where $field;
  592.         else {
  593.             $where array();
  594.             $where[$field=  $value;
  595.         }
  596.         if ($rows $this->count_rows($table,$where)) {
  597.             return $return true $rows;
  598.         }
  599.     }
  600.  
  601.     /**
  602.      * Inserts a row in the table only if there's no other row with passed in column value
  603.      * 
  604.      * @param string $table Table name
  605.      * @param string|array$field Field to use for search or array with field => fieldvalue
  606.      * @param string $value (Optional) Value to search for if $field is a string
  607.      * @param string $query Insert query
  608.      * @see row_exists()
  609.      * @return bool True on query success
  610.      */        
  611.     function insert_unique_to ($table,$field,$value,$query)
  612.     {
  613.         if !$this->row_exists($table,$field,$value) )    {
  614.             return $this->send_query($query);
  615.         else {
  616.             return false;
  617.         }
  618.     }
  619.     
  620.     /**
  621.      * Deletes a row from passed in table
  622.      * 
  623.      * @param string $table Table name
  624.      * @param string|array$where (Optional) Where statement as string or as an array of field => fieldvalue
  625.      * @return bool True when row is successfully deleted
  626.      */
  627.     function delete_from ($table,$where=''{
  628.         if (!empty($where)) {
  629.             $where "WHERE ".(is_array($where$this->array_to_string($wherestrval($where));
  630.         }
  631.         $query "DELETE FROM ".$this->table_name($table)." {$where}";
  632.         $this->query($query);
  633.         return (bool)($this->rows_affected 0);
  634.     }    
  635.     
  636.     /**
  637.      * Gets a single value from a single row from a table
  638.      * 
  639.      * @param string $table Table name
  640.      * @param string $field Field to return
  641.      * @param string|array$where (Optional) Where statement as string or as an array of field => fieldvalue
  642.      * @return mixed 
  643.      */
  644.     function get_value ($table=null,$field,$where=null{
  645.         if (!(bool)$table{
  646.             return false;
  647.         }
  648.         $query $this->select_query(array('select'=>$field,'from'=>$table,'where'=>$where))
  649.         return $this->get_var($query);
  650.     }
  651.     
  652.     /**
  653.      * Sets value of a single field in a table
  654.      * 
  655.      * @param string $table Table name
  656.      * @param string $field Field to return
  657.      * @param string $value Value to set
  658.      * @param string|array$where (Optional) Where statement as string or as an array of field => fieldvalue
  659.      * @return bool True on query success
  660.      */
  661.     function set_value ($table=null,$field,$value,$where=null{
  662.         if (!(bool)$table{
  663.             return false;
  664.         }
  665.         $query $this->update_query ($table,array("".$field=>$value),$where);
  666.         return $this->send_query($query);
  667.     }
  668.     
  669.     /**
  670.      * Returns an array of values from a single column
  671.      * 
  672.      * @param string $table Table name
  673.      * @param string $field Table column to return
  674.      * @return array|boolAn array of values or false on error
  675.      */
  676.     function get_col_values$table=null $field ){
  677.         
  678.         $table empty($table$this->table_bind : $this->table_name($table);
  679.         if (!(bool)$table{
  680.             return false;
  681.         }
  682.         $query "SHOW COLUMNS FROM `$table` LIKE '$field'";
  683.         $row $this->get_row($query,ARRAY_N);
  684.         if (count($row0{
  685.             $regex "/'(.*?)'/";
  686.             preg_match_all$regex $row[1]$enum_array );
  687.             $enum_fields $enum_array[1];
  688.             return $enum_fields;
  689.         }
  690.             return false;
  691.         }
  692.  
  693.     /*
  694.      * TABLE BINDING METHODS
  695.      */
  696.     
  697.     /**
  698.      * Adds a table to the internal table reference
  699.      * 
  700.      * Example:
  701.      * <code>
  702.      * $db->add_table(
  703.      *         '#__my_table',
  704.      *         array(
  705.      *             'id',
  706.      *             'name',
  707.      *             'surname'
  708.      *         )
  709.      * );
  710.      * </code>
  711.      * @param string $table Table name (with or without prefix)
  712.      * @param array $fields An array containing all table fields
  713.      * @param string $primary (Optional) Table primary key (defaults to 'id')
  714.      * @param bool $override (Optional) If set to true any already added table with the same name will be overwritten. Defaults to false
  715.      */
  716.     function add_table ($table,$fields=null,$primary='id',$override=false{
  717.         if (is_array($fields&& !array_key_exists($table,$this->tables|| $override === true ) ) {
  718.             if ((bool)$primary{
  719.                 $fields array_merge($fields,array('__primary'=>$primary));
  720.             }
  721.             $this->tables[$table$fields;
  722.         }
  723.     }
  724.     
  725.     /**
  726.      * Same as add_table(), but accepts as first arguments a multidimensional associative array with tables' names as keys and field array as value.
  727.      * Primary key can be marked inside the field array as a associative key __primary => 'fieldname'
  728.      * 
  729.      * Example:
  730.      * <code>
  731.      * $db->add_tables(array(
  732.      *         '#__my_table' => array (
  733.      *             'id',
  734.      *             'name',
  735.      *             'surname',
  736.      *             '__primary' => 'id'
  737.      *         ),
  738.      *         '#__my_second_table' => array (
  739.      *             [...]
  740.      *         )
  741.      * ));
  742.      * </code>
  743.      * @param array $array The multidimensional associative array of tables to insert
  744.      * @param bool $override (Optional) If set to true any already added table with the same name will be overwritten. Defaults to false.
  745.      * @see add_table()
  746.      */
  747.     function add_tables ($array=array(),$override=false{
  748.         if (!is_array($array)) {
  749.             return false;
  750.         }
  751.         foreach ($array as $table => $fields{
  752.             $this->add_table($table,$fields,null,$override);
  753.         }
  754.     }
  755.     
  756.     /**
  757.      * Selects a table from the internal table reference stored to be use with binding methods, if it exists
  758.      * 
  759.      * Example:
  760.      * <code>
  761.      * $db->bind('#__my_table');
  762.      * </code>
  763.      * @param strin $table Name of selected table
  764.      */
  765.     function bind ($table{
  766.         if (array_key_exists($table,$this->tables)) {
  767.             $this->current_table = $this->tables[$table];
  768.             $this->current_primary = $this->current_table['__primary'];
  769.             //unset($this->current_table['__primary']); TODO: add type description to tables
  770.             $this->table_bind = $this->table_name($table);     
  771.         }
  772.     }
  773.     
  774.     /**
  775.      * Returns an array of database rows from bound table
  776.      * 
  777.      * If no params are passed in all rows from the bound table are returned as an array of objects
  778.      * @param array $array (Optional) An array containing select statements
  779.      * @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
  780.      * @see get_data()
  781.      * 
  782.      * @return array|boolReturns an array with database rows or false on no results
  783.      */
  784.     function select_rows ($array=array(),$output=OBJECT{
  785.         $queryArray array_merge(array('from'=>$this->table_bind),$array);
  786.         return $this->get_data ($queryArray,$output);
  787.     }
  788.     
  789.     /**
  790.      * Counts the number of rows from bound table
  791.      * 
  792.      * @param string|array$where (Optional) where statement
  793.      * @see count_rows()
  794.      * @return int Number of rows
  795.      */
  796.     function count ($where=''{
  797.         return $this->count_rows($this->table_bind,$where);
  798.     }
  799.     
  800.     /**
  801.      * Returns true or number of occurrence of a row if it exists
  802.      * 
  803.      * @param string $val Value to search for
  804.      * @param string $col (Optional) Field to use for search. Defaults to primary key of bound table
  805.      * @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)
  806.      * @return bool|int
  807.      */
  808.     function exists ($val='',$col=null,$return=false{
  809.         //if (empty($col) || !array_key_exists($col,$this->current_table)) {TODO:see type description above
  810.         if (empty($col|| !in_array($col,$this->current_table)) {
  811.             $col $this->current_primary;
  812.         }
  813.         return $this->row_exists ($this->table_bind,$col,$val,$return);
  814.     }
  815.     
  816.     /**
  817.      * Returns an array with two given table columns as array keys and values
  818.      * 
  819.      * @param string $key1 Column name to use as key in the resulting array
  820.      * @param string $key2 Column name to use as value in the resulting array
  821.      * @param string $where (Optional) Condition to filter results
  822.      * @see get_pair()
  823.      * @return array 
  824.      */
  825.     function pair ($key1,$key2,$where=""{
  826.         return $this->get_pair ($this->table_bind,$key1,$key2,$where);
  827.     }
  828.     
  829.     /**
  830.      * Inserts a row in the bound table only if there's no other row with passed in value in current primary key
  831.      * 
  832.      * @param string $value Value to search for in primary key
  833.      * @param string $query Insert query
  834.      * @return bool True on query success
  835.      */            
  836.     function insert_unique ($value,$query{
  837.         if(is_array($query)) {
  838.             //TODO
  839.         }
  840.         return $this->insert_unique_to ($this->table_bind,$this->current_primary,$value,$query);
  841.     }
  842.  
  843.     /**
  844.      * Deletes a row from bound table
  845.      * 
  846.      * @param string $table Table name
  847.      * @param string|array$where (Optional) Where statement as string or as an array of field => fieldvalue
  848.      * @return bool True when row is successfully deleted
  849.      */    
  850.     function delete ($where='',$col=null{
  851.         if (is_int($where)) {
  852.             $where $this->current_primary.'='.$where;
  853.         }
  854.         return $this->delete_from ($this->table_bind,$where);
  855.     }
  856.     
  857.     /**
  858.      * Stores data in the bound table, either inserting a new row or updateing an existing one.
  859.      * 
  860.      * 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
  861.      * 
  862.      * Example:
  863.      * <code>
  864.      * // add a new table and bind the object to it
  865.      * $db->add_table('#__my_table',
  866.      *         array(
  867.      *             'id',
  868.      *             'name'
  869.      *         ),
  870.      *         'id' //id is the primary key
  871.      * );
  872.      * $db->bind('#__my_table');
  873.      * 
  874.      * // adds a new row
  875.      * $new_row = array('name'=>'John');
  876.      * $db->store($new_row);
  877.      * 
  878.      * // update a row
  879.      * $new_row = array('id'=>2,'name'=>'Mark');
  880.      * $db->store($new_row);
  881.      * </code>
  882.      * 
  883.      * @param array $value_array An array containing fields as keys and fields value as values
  884.      * @return bool True if query is successful, else false
  885.      */
  886.     function store ($value_array{
  887.         
  888.         // check if array's keys passed in are present in current table
  889.         $table_fields array_flip($this->current_table);
  890.         $valid_values array_intersect_key($value_array,$table_fields);
  891.         
  892.         //store query type
  893.         if (array_key_exists($this->current_primary,$valid_values)) {
  894.             $type 'update';
  895.             $update=true;
  896.             $id $valid_values[$this->current_primary];
  897.             unset($valid_values[$this->current_primary]);
  898.         else {
  899.             $update=false;
  900.             $type='insert';
  901.         }
  902.         
  903.         $query $this->build_query($this->table_bind,$valid_values,$type,$this->current_primary.'='.$id);
  904.         return $this->send_query($query,$update);
  905.     }
  906.         
  907.     /*
  908.      * COMPATIBILITY METHODS
  909.      * This methods are deprecated and mantained only for compatibility reasons to ensure
  910.      * correct functionality with old versions (<0.2) of CRUDités.
  911.      */
  912.     
  913.     /**
  914.      * @see get_where()
  915.      * @deprecated 0.2b - 03/lug/2009
  916.      */
  917.     function getWhere ($what,$table,$where=false{
  918.         return $this->get_where($what,$table,$where,ARRAY_A);
  919.     }
  920.     
  921.     /**
  922.      * @see get_where()
  923.      * @deprecated 0.2b - 03/lug/2009
  924.      */
  925.     function getObjWhere ($what,$table,$where=false{
  926.         return $this->get_where($what,$table,$where);
  927.     }
  928.  
  929.     /**
  930.      * @see array_to_string()
  931.      * @deprecated 0.2b - 03/lug/2009
  932.      */    
  933.     function arrayToString$array null$inner_glue '='$outer_glue ' AND '{
  934.         return $this->array_to_string$array$inner_glue$outer_glue);
  935.     }
  936.     
  937.     /**
  938.      * @see row_exists()
  939.      * @deprecated 0.2b - 03/lug/2009
  940.      */        
  941.     function checkTable ($table,$field,$value="",$return=false{
  942.         return $this->row_exists($table,$field,$value,$return);
  943.     }
  944.  
  945.     /**
  946.      * @see send_query()
  947.      * @deprecated 0.2b - 03/lug/2009
  948.      */        
  949.     function sendQuery ($query,$isupdate=false{
  950.         return $this->send_query($query,$isupdate);
  951.     }
  952.     
  953.     /**
  954.      * @see query_insert()
  955.      * @deprecated 0.2b - 03/lug/2009
  956.      */
  957.     function insertQuery ($table,$valueArray{
  958.         return $this->query_insert($table,$valueArray,true);
  959.     }
  960.  
  961.     /**
  962.      * @see update_query()
  963.      * @deprecated 0.2b - 03/lug/2009
  964.      */
  965.     function updateQuery ($table,$valueArray,$col,$val,$all=false{
  966.         return $this->update_query ($table,$valueArray,"{$col} = {$val}",$all,true);
  967.     }
  968.     
  969.     /**
  970.      * @see insert_unique_to()
  971.      * @deprecated 0.2b - 03/lug/2009
  972.      */
  973.     function insertAgainst ($table,$field,$value,$query{
  974.         return $this->insert_unique_to($table,$field,$value,$query);
  975.     }
  976.  
  977.     /**
  978.      * @see build_query()
  979.      * @deprecated 0.2b - 03/lug/2009
  980.      */
  981.     function buildQuery ($table,$type="insert",$col=null,$val=null{
  982.         return $this->build_query ($table,$type,"{$col} = {$val}",true);
  983.     }
  984.  
  985.     /**
  986.      * @see delete_from()
  987.      * @deprecated 0.2b - 03/lug/2009
  988.      */
  989.     function deleteRow ($table,$where{
  990.         return $this->delete_from($table,$where);
  991.     }
  992.  
  993.     /**
  994.      * @see get_pair()
  995.      * @deprecated 0.2b - 03/lug/2009
  996.      */
  997.     function getPair ($table,$key1,$key2,$where=""{
  998.             return $this->get_pair($table,$key1,$key2,$where);
  999.     }
  1000.  
  1001.     /**
  1002.      * @see flat_array()
  1003.      * @deprecated 0.2b - 03/lug/2009
  1004.      */
  1005.     function flatArray ($array,$key1=0,$key2=1{
  1006.         return $this->flat_array ($array,$key1,$key2);
  1007.     }
  1008. }
  1009. ?>

Documentation generated by phpDocumentor 1.4.2