MDB2
[ class tree: MDB2 ] [ index: MDB2 ] [ all elements ]

Source for file Extended.php

Documentation is available at Extended.php

  1. <?php
  2. // +----------------------------------------------------------------------+
  3. // | PHP versions 4 and 5                                                 |
  4. // +----------------------------------------------------------------------+
  5. // | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox,                 |
  6. // | Stig. S. Bakken, Lukas Smith                                         |
  7. // | All rights reserved.                                                 |
  8. // +----------------------------------------------------------------------+
  9. // | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
  10. // | API as well as database abstraction for PHP applications.            |
  11. // | This LICENSE is in the BSD license style.                            |
  12. // |                                                                      |
  13. // | Redistribution and use in source and binary forms, with or without   |
  14. // | modification, are permitted provided that the following conditions   |
  15. // | are met:                                                             |
  16. // |                                                                      |
  17. // | Redistributions of source code must retain the above copyright       |
  18. // | notice, this list of conditions and the following disclaimer.        |
  19. // |                                                                      |
  20. // | Redistributions in binary form must reproduce the above copyright    |
  21. // | notice, this list of conditions and the following disclaimer in the  |
  22. // | documentation and/or other materials provided with the distribution. |
  23. // |                                                                      |
  24. // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
  25. // | Lukas Smith nor the names of his contributors may be used to endorse |
  26. // | or promote products derived from this software without specific prior|
  27. // | written permission.                                                  |
  28. // |                                                                      |
  29. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
  30. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
  31. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
  32. // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
  33. // | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
  34. // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
  35. // | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
  36. // |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
  37. // | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
  38. // | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
  39. // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
  40. // | POSSIBILITY OF SUCH DAMAGE.                                          |
  41. // +----------------------------------------------------------------------+
  42. // | Author: Lukas Smith <smith@pooteeweet.org>                           |
  43. // +----------------------------------------------------------------------+
  44. //
  45. // $Id: Extended.php,v 1.60 2007/11/28 19:49:34 quipo Exp $
  46.  
  47. /**
  48.  * @package  MDB2
  49.  * @category Database
  50.  * @author   Lukas Smith <smith@pooteeweet.org>
  51.  */
  52.  
  53. /**
  54.  * Used by autoPrepare()
  55.  */
  56. define('MDB2_AUTOQUERY_INSERT'1);
  57. define('MDB2_AUTOQUERY_UPDATE'2);
  58. define('MDB2_AUTOQUERY_DELETE'3);
  59. define('MDB2_AUTOQUERY_SELECT'4);
  60.  
  61. /**
  62.  * MDB2_Extended: class which adds several high level methods to MDB2
  63.  *
  64.  * @package MDB2
  65.  * @category Database
  66.  * @author Lukas Smith <smith@pooteeweet.org>
  67.  */
  68. {
  69.     // {{{ autoPrepare()
  70.  
  71.     /**
  72.      * Generate an insert, update or delete query and call prepare() on it
  73.      *
  74.      * @param string table
  75.      * @param array the fields names
  76.      * @param int type of query to build
  77.      *                           MDB2_AUTOQUERY_INSERT
  78.      *                           MDB2_AUTOQUERY_UPDATE
  79.      *                           MDB2_AUTOQUERY_DELETE
  80.      *                           MDB2_AUTOQUERY_SELECT
  81.      * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement)
  82.      * @param array that contains the types of the placeholders
  83.      * @param mixed array that contains the types of the columns in
  84.      *                         the result set or MDB2_PREPARE_RESULT, if set to
  85.      *                         MDB2_PREPARE_MANIP the query is handled as a manipulation query
  86.      *
  87.      * @return resource handle for the query
  88.      * @see buildManipSQL
  89.      * @access public
  90.      */
  91.     function autoPrepare($table$table_fields$mode = MDB2_AUTOQUERY_INSERT,
  92.         $where = false$types = null$result_types = MDB2_PREPARE_MANIP)
  93.     {
  94.         $query $this->buildManipSQL($table$table_fields$mode$where);
  95.         if (PEAR::isError($query)) {
  96.             return $query;
  97.         }
  98.         $db =$this->getDBInstance();
  99.         if (PEAR::isError($db)) {
  100.             return $db;
  101.         }
  102.         $lobs = array();
  103.         foreach ((array)$types as $param => $type{
  104.             if (($type == 'clob'|| ($type == 'blob')) {
  105.                 $lobs[$param$table_fields[$param];
  106.             }
  107.         }
  108.         return $db->prepare($query$types$result_types$lobs);
  109.     }
  110.  
  111.     // }}}
  112.     // {{{ autoExecute()
  113.  
  114.     /**
  115.      * Generate an insert, update or delete query and call prepare() and execute() on it
  116.      *
  117.      * @param string name of the table
  118.      * @param array assoc ($key=>$value) where $key is a field name and $value its value
  119.      * @param int type of query to build
  120.      *                           MDB2_AUTOQUERY_INSERT
  121.      *                           MDB2_AUTOQUERY_UPDATE
  122.      *                           MDB2_AUTOQUERY_DELETE
  123.      *                           MDB2_AUTOQUERY_SELECT
  124.      * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement)
  125.      * @param array that contains the types of the placeholders
  126.      * @param string which specifies which result class to use
  127.      * @param mixed  array that contains the types of the columns in
  128.      *                         the result set or MDB2_PREPARE_RESULT, if set to
  129.      *                         MDB2_PREPARE_MANIP the query is handled as a manipulation query
  130.      *
  131.      * @return bool|MDB2_Errortrue on success, a MDB2 error on failure
  132.      * @see buildManipSQL
  133.      * @see autoPrepare
  134.      * @access public
  135.     */
  136.     function &autoExecute($table$fields_values$mode = MDB2_AUTOQUERY_INSERT,
  137.         $where = false$types = null$result_class = true$result_types = MDB2_PREPARE_MANIP)
  138.     {
  139.         $fields_values = (array)$fields_values;
  140.         if ($mode == MDB2_AUTOQUERY_SELECT{
  141.             if (is_array($result_types)) {
  142.                 $keys array_keys($result_types);
  143.             elseif (!empty($fields_values)) {
  144.                 $keys $fields_values;
  145.             else {
  146.                 $keys = array();
  147.             }
  148.         else {
  149.             $keys array_keys($fields_values);
  150.         }
  151.         $params array_values($fields_values);
  152.         if (empty($params)) {
  153.             $query $this->buildManipSQL($table$keys$mode$where);
  154.  
  155.             $db =$this->getDBInstance();
  156.             if (PEAR::isError($db)) {
  157.                 return $db;
  158.             }
  159.             if ($mode == MDB2_AUTOQUERY_SELECT{
  160.                 $result =$db->query($query$result_types$result_class);
  161.             else {
  162.                 $result $db->exec($query);
  163.             }
  164.         else {
  165.             $stmt $this->autoPrepare($table$keys$mode$where$types$result_types);
  166.             if (PEAR::isError($stmt)) {
  167.                 return $stmt;
  168.             }
  169.             $result =$stmt->execute($params$result_class);
  170.             $stmt->free();
  171.         }
  172.         return $result;
  173.     }
  174.  
  175.     // }}}
  176.     // {{{ buildManipSQL()
  177.  
  178.     /**
  179.      * Make automaticaly an sql query for prepare()
  180.      *
  181.      * Example : buildManipSQL('table_sql', array('field1', 'field2', 'field3'), MDB2_AUTOQUERY_INSERT)
  182.      *           will return the string : INSERT INTO table_sql (field1,field2,field3) VALUES (?,?,?)
  183.      * NB : - This belongs more to a SQL Builder class, but this is a simple facility
  184.      *      - Be carefull ! If you don't give a $where param with an UPDATE/DELETE query, all
  185.      *        the records of the table will be updated/deleted !
  186.      *
  187.      * @param string name of the table
  188.      * @param ordered array containing the fields names
  189.      * @param int type of query to build
  190.      *                           MDB2_AUTOQUERY_INSERT
  191.      *                           MDB2_AUTOQUERY_UPDATE
  192.      *                           MDB2_AUTOQUERY_DELETE
  193.      *                           MDB2_AUTOQUERY_SELECT
  194.      * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement)
  195.      *
  196.      * @return string sql query for prepare()
  197.      * @access public
  198.      */
  199.     function buildManipSQL($table$table_fields$mode$where = false)
  200.     {
  201.         $db =$this->getDBInstance();
  202.         if (PEAR::isError($db)) {
  203.             return $db;
  204.         }
  205.  
  206.         if ($db->options['quote_identifier']{
  207.             $table $db->quoteIdentifier($table);
  208.         }
  209.  
  210.         if (!empty($table_fields&& $db->options['quote_identifier']{
  211.             foreach ($table_fields as $key => $field{
  212.                 $table_fields[$key$db->quoteIdentifier($field);
  213.             }
  214.         }
  215.  
  216.         if ($where !== false && !is_null($where)) {
  217.             if (is_array($where)) {
  218.                 $where implode(' AND '$where);
  219.             }
  220.             $where ' WHERE '.$where;
  221.         }
  222.  
  223.         switch ($mode{
  224.         case MDB2_AUTOQUERY_INSERT:
  225.             if (empty($table_fields)) {
  226.                 return $db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  227.                 'Insert requires table fields'__FUNCTION__);
  228.             }
  229.             $cols implode(', '$table_fields);
  230.             $values '?'.str_repeat(', ?'(count($table_fields- 1));
  231.             return 'INSERT INTO '.$table.' ('.$cols.') VALUES ('.$values.')';
  232.             break;
  233.         case MDB2_AUTOQUERY_UPDATE:
  234.             if (empty($table_fields)) {
  235.                 return $db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  236.                 'Update requires table fields'__FUNCTION__);
  237.             }
  238.             $set implode(' = ?, '$table_fields).' = ?';
  239.             $sql 'UPDATE '.$table.' SET '.$set.$where;
  240.             return $sql;
  241.             break;
  242.         case MDB2_AUTOQUERY_DELETE:
  243.             $sql 'DELETE FROM '.$table.$where;
  244.             return $sql;
  245.             break;
  246.         case MDB2_AUTOQUERY_SELECT:
  247.             $cols !empty($table_fieldsimplode(', '$table_fields'*';
  248.             $sql 'SELECT '.$cols.' FROM '.$table.$where;
  249.             return $sql;
  250.             break;
  251.         }
  252.         return $db->raiseError(MDB2_ERROR_SYNTAXnullnull,
  253.                 'Non existant mode'__FUNCTION__);
  254.     }
  255.  
  256.     // }}}
  257.     // {{{ limitQuery()
  258.  
  259.     /**
  260.      * Generates a limited query
  261.      *
  262.      * @param string query
  263.      * @param array that contains the types of the columns in the result set
  264.      * @param integer the numbers of rows to fetch
  265.      * @param integer the row to start to fetching
  266.      * @param string which specifies which result class to use
  267.      * @param mixed   string which specifies which class to wrap results in
  268.      *
  269.      * @return MDB2_Result|MDB2_Errorresult set on success, a MDB2 error on failure
  270.      * @access public
  271.      */
  272.     function &limitQuery($query$types$limit$offset = 0$result_class = true,
  273.         $result_wrap_class = false)
  274.     {
  275.         $db =$this->getDBInstance();
  276.         if (PEAR::isError($db)) {
  277.             return $db;
  278.         }
  279.  
  280.         $result $db->setLimit($limit$offset);
  281.         if (PEAR::isError($result)) {
  282.             return $result;
  283.         }
  284.         $result =$db->query($query$types$result_class$result_wrap_class);
  285.         return $result;
  286.     }
  287.  
  288.     // }}}
  289.     // {{{ execParam()
  290.  
  291.     /**
  292.      * Execute a parameterized DML statement.
  293.      *
  294.      * @param string the SQL query
  295.      * @param array if supplied, prepare/execute will be used
  296.      *        with this array as execute parameters
  297.      * @param array that contains the types of the values defined in $params
  298.      *
  299.      * @return int|MDB2_Erroraffected rows on success, a MDB2 error on failure
  300.      * @access public
  301.      */
  302.     function execParam($query$params = array()$param_types = null)
  303.     {
  304.         $db =$this->getDBInstance();
  305.         if (PEAR::isError($db)) {
  306.             return $db;
  307.         }
  308.  
  309.         settype($params'array');
  310.         if (empty($params)) {
  311.             return $db->exec($query);
  312.         }
  313.  
  314.         $stmt $db->prepare($query$param_typesMDB2_PREPARE_MANIP);
  315.         if (PEAR::isError($stmt)) {
  316.             return $stmt;
  317.         }
  318.  
  319.         $result $stmt->execute($params);
  320.         if (PEAR::isError($result)) {
  321.             return $result;
  322.         }
  323.  
  324.         $stmt->free();
  325.         return $result;
  326.     }
  327.  
  328.     // }}}
  329.     // {{{ getOne()
  330.  
  331.     /**
  332.      * Fetch the first column of the first row of data returned from a query.
  333.      * Takes care of doing the query and freeing the results when finished.
  334.      *
  335.      * @param string the SQL query
  336.      * @param string that contains the type of the column in the result set
  337.      * @param array if supplied, prepare/execute will be used
  338.      *        with this array as execute parameters
  339.      * @param array that contains the types of the values defined in $params
  340.      * @param int|stringwhich column to return
  341.      *
  342.      * @return scalar|MDB2_Errordata on success, a MDB2 error on failure
  343.      * @access public
  344.      */
  345.     function getOne($query$type = null$params = array(),
  346.         $param_types = null$colnum = 0)
  347.     {
  348.         $db =$this->getDBInstance();
  349.         if (PEAR::isError($db)) {
  350.             return $db;
  351.         }
  352.  
  353.         settype($params'array');
  354.         settype($type'array');
  355.         if (empty($params)) {
  356.             return $db->queryOne($query$type$colnum);
  357.         }
  358.  
  359.         $stmt $db->prepare($query$param_types$type);
  360.         if (PEAR::isError($stmt)) {
  361.             return $stmt;
  362.         }
  363.  
  364.         $result $stmt->execute($params);
  365.         if (!MDB2::isResultCommon($result)) {
  366.             return $result;
  367.         }
  368.  
  369.         $one $result->fetchOne($colnum);
  370.         $stmt->free();
  371.         $result->free();
  372.         return $one;
  373.     }
  374.  
  375.     // }}}
  376.     // {{{ getRow()
  377.  
  378.     /**
  379.      * Fetch the first row of data returned from a query.  Takes care
  380.      * of doing the query and freeing the results when finished.
  381.      *
  382.      * @param string the SQL query
  383.      * @param array that contains the types of the columns in the result set
  384.      * @param array if supplied, prepare/execute will be used
  385.      *        with this array as execute parameters
  386.      * @param array that contains the types of the values defined in $params
  387.      * @param int the fetch mode to use
  388.      *
  389.      * @return array|MDB2_Errordata on success, a MDB2 error on failure
  390.      * @access public
  391.      */
  392.     function getRow($query$types = null$params = array(),
  393.         $param_types = null$fetchmode = MDB2_FETCHMODE_DEFAULT)
  394.     {
  395.         $db =$this->getDBInstance();
  396.         if (PEAR::isError($db)) {
  397.             return $db;
  398.         }
  399.  
  400.         settype($params'array');
  401.         if (empty($params)) {
  402.             return $db->queryRow($query$types$fetchmode);
  403.         }
  404.  
  405.         $stmt $db->prepare($query$param_types$types);
  406.         if (PEAR::isError($stmt)) {
  407.             return $stmt;
  408.         }
  409.  
  410.         $result $stmt->execute($params);
  411.         if (!MDB2::isResultCommon($result)) {
  412.             return $result;
  413.         }
  414.  
  415.         $row $result->fetchRow($fetchmode);
  416.         $stmt->free();
  417.         $result->free();
  418.         return $row;
  419.     }
  420.  
  421.     // }}}
  422.     // {{{ getCol()
  423.  
  424.     /**
  425.      * Fetch a single column from a result set and return it as an
  426.      * indexed array.
  427.      *
  428.      * @param string the SQL query
  429.      * @param string that contains the type of the column in the result set
  430.      * @param array if supplied, prepare/execute will be used
  431.      *        with this array as execute parameters
  432.      * @param array that contains the types of the values defined in $params
  433.      * @param int|stringwhich column to return
  434.      *
  435.      * @return array|MDB2_Errordata on success, a MDB2 error on failure
  436.      * @access public
  437.      */
  438.     function getCol($query$type = null$params = array(),
  439.         $param_types = null$colnum = 0)
  440.     {
  441.         $db =$this->getDBInstance();
  442.         if (PEAR::isError($db)) {
  443.             return $db;
  444.         }
  445.  
  446.         settype($params'array');
  447.         settype($type'array');
  448.         if (empty($params)) {
  449.             return $db->queryCol($query$type$colnum);
  450.         }
  451.  
  452.         $stmt $db->prepare($query$param_types$type);
  453.         if (PEAR::isError($stmt)) {
  454.             return $stmt;
  455.         }
  456.  
  457.         $result $stmt->execute($params);
  458.         if (!MDB2::isResultCommon($result)) {
  459.             return $result;
  460.         }
  461.  
  462.         $col $result->fetchCol($colnum);
  463.         $stmt->free();
  464.         $result->free();
  465.         return $col;
  466.     }
  467.  
  468.     // }}}
  469.     // {{{ getAll()
  470.  
  471.     /**
  472.      * Fetch all the rows returned from a query.
  473.      *
  474.      * @param string the SQL query
  475.      * @param array that contains the types of the columns in the result set
  476.      * @param array if supplied, prepare/execute will be used
  477.      *        with this array as execute parameters
  478.      * @param array that contains the types of the values defined in $params
  479.      * @param int the fetch mode to use
  480.      * @param bool if set to true, the $all will have the first
  481.      *        column as its first dimension
  482.      * @param bool $force_array used only when the query returns exactly
  483.      *        two columns. If true, the values of the returned array will be
  484.      *        one-element arrays instead of scalars.
  485.      * @param bool $group if true, the values of the returned array is
  486.      *        wrapped in another array.  If the same key value (in the first
  487.      *        column) repeats itself, the values will be appended to this array
  488.      *        instead of overwriting the existing values.
  489.      *
  490.      * @return array|MDB2_Errordata on success, a MDB2 error on failure
  491.      * @access public
  492.      */
  493.     function getAll($query$types = null$params = array(),
  494.         $param_types = null$fetchmode = MDB2_FETCHMODE_DEFAULT,
  495.         $rekey = false$force_array = false$group = false)
  496.     {
  497.         $db =$this->getDBInstance();
  498.         if (PEAR::isError($db)) {
  499.             return $db;
  500.         }
  501.  
  502.         settype($params'array');
  503.         if (empty($params)) {
  504.             return $db->queryAll($query$types$fetchmode$rekey$force_array$group);
  505.         }
  506.  
  507.         $stmt $db->prepare($query$param_types$types);
  508.         if (PEAR::isError($stmt)) {
  509.             return $stmt;
  510.         }
  511.  
  512.         $result $stmt->execute($params);
  513.         if (!MDB2::isResultCommon($result)) {
  514.             return $result;
  515.         }
  516.  
  517.         $all $result->fetchAll($fetchmode$rekey$force_array$group);
  518.         $stmt->free();
  519.         $result->free();
  520.         return $all;
  521.     }
  522.  
  523.     // }}}
  524.     // {{{ getAssoc()
  525.  
  526.     /**
  527.      * Fetch the entire result set of a query and return it as an
  528.      * associative array using the first column as the key.
  529.      *
  530.      * If the result set contains more than two columns, the value
  531.      * will be an array of the values from column 2-n.  If the result
  532.      * set contains only two columns, the returned value will be a
  533.      * scalar with the value of the second column (unless forced to an
  534.      * array with the $force_array parameter).  A MDB2 error code is
  535.      * returned on errors.  If the result set contains fewer than two
  536.      * columns, a MDB2_ERROR_TRUNCATED error is returned.
  537.      *
  538.      * For example, if the table 'mytable' contains:
  539.      * <pre>
  540.      *   ID      TEXT       DATE
  541.      * --------------------------------
  542.      *   1       'one'      944679408
  543.      *   2       'two'      944679408
  544.      *   3       'three'    944679408
  545.      * </pre>
  546.      * Then the call getAssoc('SELECT id,text FROM mytable') returns:
  547.      * <pre>
  548.      *    array(
  549.      *      '1' => 'one',
  550.      *      '2' => 'two',
  551.      *      '3' => 'three',
  552.      *    )
  553.      * </pre>
  554.      * ...while the call getAssoc('SELECT id,text,date FROM mytable') returns:
  555.      * <pre>
  556.      *    array(
  557.      *      '1' => array('one', '944679408'),
  558.      *      '2' => array('two', '944679408'),
  559.      *      '3' => array('three', '944679408')
  560.      *    )
  561.      * </pre>
  562.      *
  563.      * If the more than one row occurs with the same value in the
  564.      * first column, the last row overwrites all previous ones by
  565.      * default.  Use the $group parameter if you don't want to
  566.      * overwrite like this.  Example:
  567.      * <pre>
  568.      * getAssoc('SELECT category,id,name FROM mytable', null, null
  569.      *           MDB2_FETCHMODE_ASSOC, false, true) returns:
  570.      *    array(
  571.      *      '1' => array(array('id' => '4', 'name' => 'number four'),
  572.      *                   array('id' => '6', 'name' => 'number six')
  573.      *             ),
  574.      *      '9' => array(array('id' => '4', 'name' => 'number four'),
  575.      *                   array('id' => '6', 'name' => 'number six')
  576.      *             )
  577.      *    )
  578.      * </pre>
  579.      *
  580.      * Keep in mind that database functions in PHP usually return string
  581.      * values for results regardless of the database's internal type.
  582.      *
  583.      * @param string the SQL query
  584.      * @param array that contains the types of the columns in the result set
  585.      * @param array if supplied, prepare/execute will be used
  586.      *        with this array as execute parameters
  587.      * @param array that contains the types of the values defined in $params
  588.      * @param bool $force