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

Source for file mysql.php

Documentation is available at mysql.php

  1. <?php
  2. // vim: set et ts=4 sw=4 fdm=marker:
  3. // +----------------------------------------------------------------------+
  4. // | PHP versions 4 and 5                                                 |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox,                 |
  7. // | Stig. S. Bakken, Lukas Smith                                         |
  8. // | All rights reserved.                                                 |
  9. // +----------------------------------------------------------------------+
  10. // | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
  11. // | API as well as database abstraction for PHP applications.            |
  12. // | This LICENSE is in the BSD license style.                            |
  13. // |                                                                      |
  14. // | Redistribution and use in source and binary forms, with or without   |
  15. // | modification, are permitted provided that the following conditions   |
  16. // | are met:                                                             |
  17. // |                                                                      |
  18. // | Redistributions of source code must retain the above copyright       |
  19. // | notice, this list of conditions and the following disclaimer.        |
  20. // |                                                                      |
  21. // | Redistributions in binary form must reproduce the above copyright    |
  22. // | notice, this list of conditions and the following disclaimer in the  |
  23. // | documentation and/or other materials provided with the distribution. |
  24. // |                                                                      |
  25. // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
  26. // | Lukas Smith nor the names of his contributors may be used to endorse |
  27. // | or promote products derived from this software without specific prior|
  28. // | written permission.                                                  |
  29. // |                                                                      |
  30. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
  31. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
  32. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
  33. // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
  34. // | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
  35. // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
  36. // | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
  37. // |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
  38. // | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
  39. // | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
  40. // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
  41. // | POSSIBILITY OF SUCH DAMAGE.                                          |
  42. // +----------------------------------------------------------------------+
  43. // | Author: Lukas Smith <smith@pooteeweet.org>                           |
  44. // +----------------------------------------------------------------------+
  45. //
  46. // $Id: mysql.php,v 1.176 2007/03/10 09:58:01 quipo Exp $
  47. //
  48.  
  49. /**
  50.  * MDB2 MySQL driver
  51.  *
  52.  * @package MDB2
  53.  * @category Database
  54.  * @author  Lukas Smith <smith@pooteeweet.org>
  55.  */
  56. class MDB2_Driver_mysql extends MDB2_Driver_Common
  57. {
  58.     // {{{ properties
  59.     var $string_quoting = array('start' => "'"'end' => "'"'escape' => '\\''escape_pattern' => '\\');
  60.  
  61.     var $identifier_quoting = array('start' => '`''end' => '`''escape' => '`');
  62.  
  63.     var $sql_comments = array(
  64.         array('start' => '-- ''end' => "\n"'escape' => false),
  65.         array('start' => '#''end' => "\n"'escape' => false),
  66.         array('start' => '/*''end' => '*/''escape' => false),
  67.     );
  68.  
  69.     var $start_transaction = false;
  70.  
  71.     var $varchar_max_length = 255;
  72.     // }}}
  73.     // {{{ constructor
  74.  
  75.     /**
  76.      * Constructor
  77.      */
  78.     function __construct()
  79.     {
  80.         parent::__construct();
  81.  
  82.         $this->phptype 'mysql';
  83.         $this->dbsyntax 'mysql';
  84.  
  85.         $this->supported['sequences''emulated';
  86.         $this->supported['indexes'= true;
  87.         $this->supported['affected_rows'= true;
  88.         $this->supported['transactions'= false;
  89.         $this->supported['savepoints'= false;
  90.         $this->supported['summary_functions'= true;
  91.         $this->supported['order_by_text'= true;
  92.         $this->supported['current_id''emulated';
  93.         $this->supported['limit_queries'= true;
  94.         $this->supported['LOBs'= true;
  95.         $this->supported['replace'= true;
  96.         $this->supported['sub_selects''emulated';
  97.         $this->supported['auto_increment'= true;
  98.         $this->supported['primary_key'= true;
  99.         $this->supported['result_introspection'= true;
  100.         $this->supported['prepared_statements''emulated';
  101.         $this->supported['identifier_quoting'= true;
  102.         $this->supported['pattern_escaping'= true;
  103.         $this->supported['new_link'= true;
  104.  
  105.         $this->options['default_table_type''';
  106.     }
  107.  
  108.     // }}}
  109.     // {{{ errorInfo()
  110.  
  111.     /**
  112.      * This method is used to collect information about an error
  113.      *
  114.      * @param integer $error 
  115.      * @return array 
  116.      * @access public
  117.      */
  118.     function errorInfo($error = null)
  119.     {
  120.         if ($this->connection{
  121.             $native_code @mysql_errno($this->connection);
  122.             $native_msg  @mysql_error($this->connection);
  123.         else {
  124.             $native_code @mysql_errno();
  125.             $native_msg  @mysql_error();
  126.         }
  127.         if (is_null($error)) {
  128.             static $ecode_map;
  129.             if (empty($ecode_map)) {
  130.                 $ecode_map = array(
  131.                     1004 => MDB2_ERROR_CANNOT_CREATE,
  132.                     1005 => MDB2_ERROR_CANNOT_CREATE,
  133.                     1006 => MDB2_ERROR_CANNOT_CREATE,
  134.                     1007 => MDB2_ERROR_ALREADY_EXISTS,
  135.                     1008 => MDB2_ERROR_CANNOT_DROP,
  136.                     1022 => MDB2_ERROR_ALREADY_EXISTS,
  137.                     1044 => MDB2_ERROR_ACCESS_VIOLATION,
  138.                     1046 => MDB2_ERROR_NODBSELECTED,
  139.                     1048 => MDB2_ERROR_CONSTRAINT,
  140.                     1049 => MDB2_ERROR_NOSUCHDB,
  141.                     1050 => MDB2_ERROR_ALREADY_EXISTS,
  142.                     1051 => MDB2_ERROR_NOSUCHTABLE,
  143.                     1054 => MDB2_ERROR_NOSUCHFIELD,
  144.                     1061 => MDB2_ERROR_ALREADY_EXISTS,
  145.                     1062 => MDB2_ERROR_ALREADY_EXISTS,
  146.                     1064 => MDB2_ERROR_SYNTAX,
  147.                     1091 => MDB2_ERROR_NOT_FOUND,
  148.                     1100 => MDB2_ERROR_NOT_LOCKED,
  149.                     1136 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
  150.                     1142 => MDB2_ERROR_ACCESS_VIOLATION,
  151.                     1146 => MDB2_ERROR_NOSUCHTABLE,
  152.                     1216 => MDB2_ERROR_CONSTRAINT,
  153.                     1217 => MDB2_ERROR_CONSTRAINT,
  154.                     1356 => MDB2_ERROR_DIVZERO,
  155.                     1451 => MDB2_ERROR_CONSTRAINT,
  156.                     1452 => MDB2_ERROR_CONSTRAINT,
  157.                 );
  158.             }
  159.             if ($this->options['portability'MDB2_PORTABILITY_ERRORS{
  160.                 $ecode_map[1022= MDB2_ERROR_CONSTRAINT;
  161.                 $ecode_map[1048= MDB2_ERROR_CONSTRAINT_NOT_NULL;
  162.                 $ecode_map[1062= MDB2_ERROR_CONSTRAINT;
  163.             else {
  164.                 // Doing this in case mode changes during runtime.
  165.                 $ecode_map[1022= MDB2_ERROR_ALREADY_EXISTS;
  166.                 $ecode_map[1048= MDB2_ERROR_CONSTRAINT;
  167.                 $ecode_map[1062= MDB2_ERROR_ALREADY_EXISTS;
  168.             }
  169.             if (isset($ecode_map[$native_code])) {
  170.                 $error $ecode_map[$native_code];
  171.             }
  172.         }
  173.         return array($error$native_code$native_msg);
  174.     }
  175.  
  176.     // }}}
  177.     // {{{ escape()
  178.  
  179.     /**
  180.      * Quotes a string so it can be safely used in a query. It will quote
  181.      * the text so it can safely be used within a query.
  182.      *
  183.      * @param   string  the input string to quote
  184.      * @param   bool    escape wildcards
  185.      *
  186.      * @return  string  quoted string
  187.      *
  188.      * @access  public
  189.      */
  190.     function escape($text$escape_wildcards = false)
  191.     {
  192.         if ($escape_wildcards{
  193.             $text $this->escapePattern($text);
  194.         }
  195.         $connection $this->getConnection();
  196.         if (PEAR::isError($connection)) {
  197.             return $connection;
  198.         }
  199.         $text @mysql_real_escape_string($text$connection);
  200.         return $text;
  201.     }
  202.  
  203.     // }}}
  204.     // {{{
  205.  
  206.     /**
  207.      * Start a transaction or set a savepoint.
  208.      *
  209.      * @param   string  name of a savepoint to set
  210.      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
  211.      *
  212.      * @access  public
  213.      */
  214.     function beginTransaction($savepoint = null)
  215.     {
  216.         $this->debug('Starting transaction/savepoint'__FUNCTION__array('is_manip' => true'savepoint' => $savepoint));
  217.         $this->_getServerCapabilities();
  218.         if (!is_null($savepoint)) {
  219.             if (!$this->supports('savepoints')) {
  220.                 return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  221.                     'savepoints are not supported'__FUNCTION__);
  222.             }
  223.             if (!$this->in_transaction{
  224.                 return $this->raiseError(MDB2_ERROR_INVALIDnullnull,
  225.                     'savepoint cannot be released when changes are auto committed'__FUNCTION__);
  226.             }
  227.             $query 'SAVEPOINT '.$savepoint;
  228.             return $this->_doQuery($querytrue);
  229.         elseif ($this->in_transaction{
  230.             return MDB2_OK;  //nothing to do
  231.         }
  232.         if (!$this->destructor_registered && $this->opened_persistent{
  233.             $this->destructor_registered = true;
  234.             register_shutdown_function('MDB2_closeOpenTransactions');
  235.         }
  236.         $query $this->start_transaction ? 'START TRANSACTION' 'SET AUTOCOMMIT = 1';
  237.         $result =$this->_doQuery($querytrue);
  238.         if (PEAR::isError($result)) {
  239.             return $result;
  240.         }
  241.         $this->in_transaction = true;
  242.         return MDB2_OK;
  243.     }
  244.  
  245.     // }}}
  246.     // {{{ commit()
  247.  
  248.     /**
  249.      * Commit the database changes done during a transaction that is in
  250.      * progress or release a savepoint. This function may only be called when
  251.      * auto-committing is disabled, otherwise it will fail. Therefore, a new
  252.      * transaction is implicitly started after committing the pending changes.
  253.      *
  254.      * @param   string  name of a savepoint to release
  255.      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
  256.      *
  257.      * @access  public
  258.      */
  259.     function commit($savepoint = null)
  260.     {
  261.         $this->debug('Committing transaction/savepoint'__FUNCTION__array('is_manip' => true'savepoint' => $savepoint));
  262.         if (!$this->in_transaction{
  263.             return $this->raiseError(MDB2_ERROR_INVALIDnullnull,
  264.                 'commit/release savepoint cannot be done changes are auto committed'__FUNCTION__);
  265.         }
  266.         if (!is_null($savepoint)) {
  267.             if (!$this->supports('savepoints')) {
  268.                 return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  269.                     'savepoints are not supported'__FUNCTION__);
  270.             }
  271.             $server_info $this->getServerVersion();
  272.             if (version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch']'5.0.3''<')) {
  273.                 return MDB2_OK;
  274.             }
  275.             $query 'RELEASE SAVEPOINT '.$savepoint;
  276.             return $this->_doQuery($querytrue);
  277.         }
  278.  
  279.         if (!$this->supports('transactions')) {
  280.             return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  281.                 'transactions are not supported'__FUNCTION__);
  282.         }
  283.  
  284.         $result =$this->_doQuery('COMMIT'true);
  285.         if (PEAR::isError($result)) {
  286.             return $result;
  287.         }
  288.         if (!$this->start_transaction{
  289.             $query 'SET AUTOCOMMIT = 0';
  290.             $result =$this->_doQuery($querytrue);
  291.             if (PEAR::isError($result)) {
  292.                 return $result;
  293.             }
  294.         }
  295.         $this->in_transaction = false;
  296.         return MDB2_OK;
  297.     }
  298.  
  299.     // }}}
  300.     // {{{ rollback()
  301.  
  302.     /**
  303.      * Cancel any database changes done during a transaction or since a specific
  304.      * savepoint that is in progress. This function may only be called when
  305.      * auto-committing is disabled, otherwise it will fail. Therefore, a new
  306.      * transaction is implicitly started after canceling the pending changes.
  307.      *
  308.      * @param   string  name of a savepoint to rollback to
  309.      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
  310.      *
  311.      * @access  public
  312.      */
  313.     function rollback($savepoint = null)
  314.     {
  315.         $this->debug('Rolling back transaction/savepoint'__FUNCTION__array('is_manip' => true'savepoint' => $savepoint));
  316.         if (!$this->in_transaction{
  317.             return $this->raiseError(MDB2_ERROR_INVALIDnullnull,
  318.                 'rollback cannot be done changes are auto committed'__FUNCTION__);
  319.         }
  320.         if (!is_null($savepoint)) {
  321.             if (!$this->supports('savepoints')) {
  322.                 return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  323.                     'savepoints are not supported'__FUNCTION__);
  324.             }
  325.             $query 'ROLLBACK TO SAVEPOINT '.$savepoint;
  326.             return $this->_doQuery($querytrue);
  327.         }
  328.  
  329.         $query 'ROLLBACK';
  330.         $result =$this->_doQuery($querytrue);
  331.         if (PEAR::isError($result)) {
  332.             return $result;
  333.         }
  334.         if (!$this->start_transaction{
  335.             $query 'SET AUTOCOMMIT = 0';
  336.             $result =$this->_doQuery($querytrue);
  337.             if (PEAR::isError($result)) {
  338.                 return $result;
  339.             }
  340.         }
  341.         $this->in_transaction = false;
  342.         return MDB2_OK;
  343.     }
  344.  
  345.     // }}}
  346.     // {{{ function setTransactionIsolation()
  347.  
  348.     /**
  349.      * Set the transacton isolation level.
  350.      *
  351.      * @param   string  standard isolation level
  352.      *                   READ UNCOMMITTED (allows dirty reads)
  353.      *                   READ COMMITTED (prevents dirty reads)
  354.      *                   REPEATABLE READ (prevents nonrepeatable reads)
  355.      *                   SERIALIZABLE (prevents phantom reads)
  356.      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
  357.      *
  358.      * @access  public
  359.      * @since   2.1.1
  360.      */
  361.     function setTransactionIsolation($isolation)
  362.     {
  363.         $this->debug('Setting transaction isolation level'__FUNCTION__array('is_manip' => true));
  364.         if (!$this->supports('transactions')) {
  365.             return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  366.                 'transactions are not supported'__FUNCTION__);
  367.         }
  368.         switch ($isolation{
  369.         case 'READ UNCOMMITTED':
  370.         case 'READ COMMITTED':
  371.         case 'REPEATABLE READ':
  372.         case 'SERIALIZABLE':
  373.             break;
  374.         default:
  375.             return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  376.                 'isolation level is not supported: '.$isolation__FUNCTION__);
  377.         }
  378.  
  379.         $query = "SET SESSION TRANSACTION ISOLATION LEVEL $isolation";
  380.         return $this->_doQuery($querytrue);
  381.     }
  382.  
  383.     // }}}
  384.     // {{{ connect()
  385.  
  386.     /**
  387.      * Connect to the database
  388.      *
  389.      * @return true on success, MDB2 Error Object on failure
  390.      */
  391.     function connect()
  392.     {
  393.         if (is_resource($this->connection)) {
  394.             if (count(array_diff($this->connected_dsn$this->dsn)) == 0
  395.                 && $this->opened_persistent == $this->options['persistent']
  396.             {
  397.                 return MDB2_OK;
  398.             }
  399.             $this->disconnect(false);
  400.         }
  401.  
  402.         if (!PEAR::loadExtension($this->phptype)) {
  403.             return $this->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  404.                 'extension '.$this->phptype.' is not compiled into PHP'__FUNCTION__);
  405.         }
  406.  
  407.         $params = array();
  408.         if ($this->dsn['protocol'&& $this->dsn['protocol'== 'unix'{
  409.             $params[0':' $this->dsn['socket'];
  410.         else {
  411.             $params[0$this->dsn['hostspec'$this->dsn['hostspec']
  412.                          : 'localhost';
  413.             if ($this->dsn['port']{
  414.                 $params[0].= ':' $this->dsn['port'];
  415.             }
  416.         }
  417.         $params[$this->dsn['username'$this->dsn['username': null;
  418.         $params[$this->dsn['password'$this->dsn['password': null;
  419.         if (!$this->options['persistent']{
  420.             if (isset($this->dsn['new_link'])
  421.                 && ($this->dsn['new_link'== 'true' || $this->dsn['new_link'=== true)
  422.             {
  423.                 $params[= true;
  424.             else {
  425.                 $params[= false;
  426.             }
  427.         }
  428.         if (version_compare(phpversion()'4.3.0''>=')) {
  429.             $params[= isset($this->dsn['client_flags'])
  430.                 ? $this->dsn['client_flags': null;
  431.         }
  432.         $connect_function $this->options['persistent''mysql_pconnect' 'mysql_connect';
  433.  
  434.         $connection @call_user_func_array($connect_function$params);
  435.         if (!$connection{
  436.             if (($err @mysql_error()) != ''{
  437.                 return $this->raiseError(MDB2_ERROR_CONNECT_FAILEDnullnull,
  438.                     $err__FUNCTION__);
  439.             else {
  440.                 return $this->raiseError(MDB2_ERROR_CONNECT_FAILEDnullnull,
  441.                     'unable to establish a connection'__FUNCTION__);
  442.             }
  443.         }
  444.  
  445.         if (!empty($this->dsn['charset'])) {
  446.             $result $this->setCharset($this->dsn['charset']$connection);
  447.             if (PEAR::isError($result)) {
  448.                 return $result;
  449.             }
  450.         }
  451.  
  452.         $this->connection $connection;
  453.         $this->connected_dsn $this->dsn;
  454.         $this->connected_database_name '';
  455.         $this->opened_persistent $this->options['persistent'];
  456.         $this->dbsyntax $this->dsn['dbsyntax'$this->dsn['dbsyntax'$this->phptype;
  457.  
  458.         if ($this->database_name{
  459.             if ($this->database_name != $this->connected_database_name{
  460.                 if (!@mysql_select_db($this->database_name$connection)) {
  461.                     $err $this->raiseError(nullnullnull,
  462.                         'Could not select the database: '.$this->database_name__FUNCTION__);
  463.                     return $err;
  464.                 }
  465.                 $this->connected_database_name $this->database_name;
  466.             }
  467.         }
  468.  
  469.         $this->supported['transactions'$this->options['use_transactions'];
  470.         if ($this->options['default_table_type']{
  471.             switch (strtoupper($this->options['default_table_type'])) {
  472.             case 'BLACKHOLE':
  473.             case 'MEMORY':
  474.             case 'ARCHIVE':
  475.             case 'CSV':
  476.             case 'HEAP':
  477.             case 'ISAM':
  478.             case 'MERGE':
  479.             case 'MRG_ISAM':
  480.             case 'ISAM':
  481.             case 'MRG_MYISAM':
  482.             case 'MYISAM':
  483.                 $this->supported['transactions'= false;
  484.                 $this->warnings[$this->options['default_table_type'.
  485.                     ' is not a supported default table type';
  486.                 break;
  487.             }
  488.         }
  489.  
  490.         $this->supported['sub_selects''emulated';
  491.         $this->supported['prepared_statements''emulated';
  492.         $this->start_transaction = false;
  493.         $this->varchar_max_length = 255;
  494.         
  495.         $this->_getServerCapabilities();
  496.  
  497.         return MDB2_OK;
  498.     }
  499.     // }}}
  500.     // {{{ setCharset()
  501.  
  502.     /**
  503.      * Set the charset on the current connection
  504.      *
  505.      * @param string    charset
  506.      * @param resource  connection handle
  507.      *
  508.      * @return true on success, MDB2 Error Object on failure
  509.      */
  510.     function setCharset($charset$connection = null)
  511.     {
  512.         if (is_null($connection)) {
  513.             $connection $this->getConnection();
  514.             if (PEAR::isError($connection)) {
  515.                 return $connection;
  516.             }
  517.         }
  518.         $query "SET NAMES '".mysql_real_escape_string($charset$connection)."'";
  519.         return $this->_doQuery($querytrue$connection);
  520.     }
  521.  
  522.     // }}}
  523.     // {{{ disconnect()
  524.  
  525.     /**
  526.      * Log out and disconnect from the database.
  527.      *
  528.      * @param  boolean $force if the disconnect should be forced even if the
  529.      *                         connection is opened persistently
  530.      * @return mixed true on success, false if not connected and error
  531.      *                 object on error
  532.      * @access public
  533.      */
  534.     function disconnect($force = true)
  535.     {
  536.         if (is_resource($this->connection)) {
  537.             if ($this->in_transaction{
  538.                 $dsn $this->dsn;
  539.                 $database_name $this->database_name;
  540.                 $persistent $this->options['persistent'];
  541.                 $this->dsn $this->connected_dsn;
  542.                 $this->database_name $this->connected_database_name;
  543.                 $this->options['persistent'$this->opened_persistent;
  544.                 $this->rollback();
  545.                 $this->dsn $dsn;
  546.                 $this->database_name $database_name;
  547.                 $this->options['persistent'$persistent;
  548.             }
  549.  
  550.             if (!$this->opened_persistent || $force{
  551.                 @mysql_close($this->connection);
  552.             }
  553.         }
  554.         return parent::disconnect($force);
  555.     }
  556.  
  557.     // }}}
  558.     // {{{ _doQuery()
  559.  
  560.     /**
  561.      * Execute a query
  562.      * @param string $query  query
  563.      * @param boolean $is_manip  if the query is a manipulation query
  564.      * @param resource $connection 
  565.      * @param string $database_name 
  566.      * @return result or error object
  567.      * @access protected
  568.      */
  569.     function &_doQuery($query$is_manip = false$connection = null$database_name = null)
  570.     {
  571.         $this->last_query $query;
  572.         $result $this->debug($query'query'array('is_manip' => $is_manip'when' => 'pre'));
  573.         if ($result{
  574.             if (PEAR::isError($result)) {
  575.                 return $result;
  576.             }
  577.             $query $result;
  578.         }
  579.         if ($this->options['disable_query']{
  580.             $result $is_manip ? 0 : null;
  581.             return $result;
  582.         }
  583.  
  584.         if (is_null($connection)) {
  585.             $connection $this->getConnection();
  586.             if (PEAR::isError($connection)) {
  587.                 return $connection;
  588.             }
  589.         }
  590.         if (is_null($database_name)) {
  591.             $database_name $this->database_name;
  592.         }
  593.  
  594.         if ($database_name{
  595.             if ($database_name != $this->connected_database_name{
  596.                 if (!@mysql_select_db($database_name$connection)) {
  597.                     $err $this->raiseError(nullnullnull,
  598.                         'Could not select the database: '.$database_name__FUNCTION__);
  599.                     return $err;
  600.                 }
  601.                 $this->connected_database_name $database_name;
  602.             }
  603.         }
  604.  
  605.         $function $this->options['result_buffering']
  606.             ? 'mysql_query' 'mysql_unbuffered_query';
  607.         $result @$function($query$connection);
  608.         if (!$result{
  609.             $err =$this->raiseError(nullnullnull,
  610.                 'Could not execute statement'__FUNCTION__);
  611.             return $err;
  612.         }
  613.  
  614.         $this->debug($query'query'array('is_manip' => $is_manip'when' => 'post''result' => $result));
  615.         return $result;
  616.     }
  617.  
  618.     // }}}
  619.     // {{{ _affectedRows()
  620.  
  621.     /**
  622.      * Returns the number of rows affected
  623.      *
  624.      * @param resource $result 
  625.      * @param resource $connection 
  626.      * @return mixed MDB2 Error Object or the number of rows affected
  627.      * @access private
  628.      */
  629.     function _affectedRows($connection$result = null)
  630.     {
  631.         if (is_null($connection)) {
  632.             $connection $this->getConnection();
  633.             if (PEAR::isError($connection)) {
  634.                 return $connection;
  635.             }
  636.         }
  637.         return @mysql_affected_rows($connection);
  638.     }
  639.  
  640.     // }}}
  641.     // {{{ _modifyQuery()
  642.  
  643.     /**
  644.      * Changes a query string for various DBMS specific reasons
  645.      *
  646.      * @param string $query  query to modify
  647.      * @param boolean $is_manip  if it is a DML query
  648.      * @param integer $limit  limit the number of rows
  649.      * @param integer $offset  start reading from given offset
  650.      * @return string modified query
  651.      * @access protected
  652.      */
  653.     function _modifyQuery($query$is_manip$limit$offset)
  654.     {
  655.         if ($this->options['portability'MDB2_PORTABILITY_DELETE_COUNT{
  656.             // "DELETE FROM table" gives 0 affected rows in MySQL.
  657.             // This little hack lets you know how many rows were deleted.
  658.             if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i'$query)) {
  659.                 $query preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
  660.                                       'DELETE FROM \1 WHERE 1=1'$query);
  661.             }
  662.         }
  663.         if ($limit > 0
  664.             && !preg_match('/LIMIT\s*\d(\s*(,|OFFSET)\s*\d+)?/i'$query)
  665.         {
  666.             $query rtrim($query);
  667.             if (substr($query-1== ';'{
  668.                 $query substr($query0-1);
  669.             }
  670.             if ($is_manip{
  671.                 return $query . " LIMIT $limit";
  672.             else {
  673.                 return $query . " LIMIT $offset$limit";
  674.             }
  675.         }
  676.         return $query;
  677.     }
  678.  
  679.     // }}}
  680.     // {{{ getServerVersion()
  681.  
  682.     /**
  683.      * return version information about the server
  684.      *
  685.      * @param bool   $native  determines if the raw version string should be returned
  686.      * @return mixed array/string with version information or MDB2 error object
  687.      * @access public
  688.      */
  689.     function getServerVersion($native = false)
  690.     {
  691.         $connection $this->getConnection();
  692.         if (PEAR::isError($connection)) {
  693.             return $connection;
  694.         }
  695.         if ($this->connected_server_info{
  696.             $server_info $this->connected_server_info;
  697.         else {
  698.             $server_info @mysql_get_server_info($connection);
  699.         }
  700.         if (!$server_info{
  701.             return $this->raiseError(nullnullnull,
  702.                 'Could not get server information'__FUNCTION__);
  703.         }
  704.         // cache server_info
  705.         $this->connected_server_info $server_info;
  706.         if (!$native{
  707.             $tmp explode('.'$server_info3);
  708.             if (isset($tmp[2]&& strpos($tmp[2]'-')) {
  709.                 $tmp2 explode('-'@$tmp[2]2);
  710.             else {
  711.                 $tmp2[0= isset($tmp[2]$tmp[2: null;
  712.                 $tmp2[1= null;
  713.             }
  714.             $server_info = array(
  715.                 'major' => isset($tmp[0]$tmp[0: null,
  716.                 'minor' => isset($tmp[1]$tmp[1: null,
  717.                 'patch' => $tmp2[0],
  718.                 'extra' => $tmp2[1],
  719.                 'native' => $server_info,
  720.             );
  721.         }
  722.         return $server_info;
  723.     }
  724.  
  725.     // }}}
  726.     // {{{ _getServerCapabilities()
  727.  
  728.     /**
  729.      * Fetch some information about the server capabilities
  730.      * (transactions, subselects, prepared statements, etc).
  731.      *
  732.      * @access private
  733.      */
  734.     function _getServerCapabilities()
  735.     {
  736.         static $already_checked = false;
  737.         if (!$already_checked{
  738.             $already_checked = true;
  739.             $server_info $this->getServerVersion();
  740.             if (is_array($server_info)) {
  741.                 if (!version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch']'4.1.0''<')) {
  742.                     $this->supported['sub_selects'= true;
  743.                     $this->supported['prepared_statements'= true;
  744.                 }
  745.  
  746.                 if (!version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch']'4.0.14''<')
  747.                     || !version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch']'4.1.1''<')
  748.                 {
  749.                     $this->supported['savepoints'= true;
  750.                 }
  751.  
  752.                 if (!version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch']'4.0.11''<')) {
  753.                     $this->start_transaction = true;
  754.                 }
  755.  
  756.                 if (!version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch']'5.0.3''<')) {
  757.                     $this->varchar_max_length = 65532;
  758.                 }
  759.             }
  760.         }
  761.     }
  762.  
  763.     // }}}
  764.     // {{{ function _skipUserDefinedVariable($query, $position)
  765.  
  766.     /**
  767. /**
  768.      * Utility method, used by prepare() to avoid misinterpreting MySQL user
  769.      * defined variables (SELECT @x:=5) for placeholders.
  770.      * Check if the placeholder is a false positive, i.e. if it is an user defined
  771.      * variable instead. If so, skip it and advance the position, otherwise
  772.      * return the current position, which is valid
  773.      *
  774.      * @param string $query 
  775.      * @param integer $position current string cursor position
  776.      * @return integer $new_position
  777.      * @access protected
  778.      */
  779.     function _skipUserDefinedVariable($query$position)
  780.     {
  781.         $found = strpos(strrev(substr($query0$position))'@');
  782.         if ($found === false{
  783.             return $position;
  784.         }
  785.         $pos strlen($querystrlen(substr($query$position)) $found - 1;
  786.         $substring substr($query$pos$position $pos + 2);
  787.         if (preg_match('/^@\w+:=$/'$substring)) {
  788.             return $position + 1; //found an user defined variable: skip it
  789.         }
  790.         return $position;
  791.     }
  792.  
  793.     // }}}
  794.     // {{{ prepare()
  795.  
  796.     /**
  797.      * Prepares a query for multiple execution with execute().
  798.      * With some database backends, this is emulated.
  799.      * prepare() requires a generic query as string like
  800.      * 'INSERT INTO numbers VALUES(?,?)' or
  801.      * 'INSERT INTO numbers VALUES(:foo,:bar)'.
  802.      * The ? and :[a-zA-Z] and  are placeholders which can be set using
  803.      * bindParam() and the query can be send off using the execute() method.
  804.      *
  805.      * @param string $query the query to prepare
  806.      * @param mixed   $types  array that contains the types of the placeholders
  807.      * @param mixed   $result_types  array that contains the types of the columns in
  808.      *                         the result set or MDB2_PREPARE_RESULT, if set to
  809.      *                         MDB2_PREPARE_MANIP the query is handled as a manipulation query
  810.      * @param mixed   $lobs   key (field) value (parameter) pair for all lob placeholders
  811.      * @return mixed resource handle for the prepared query on success, a MDB2
  812.      *         error on failure
  813.      * @access public
  814.      * @see bindParam, execute
  815.      */
  816.     function &prepare($query$types = null$result_types = null$lobs = array())
  817.     {
  818.         if ($this->options['emulate_prepared']
  819.             || $this->supported['prepared_statements'!== true
  820.         {
  821.             $obj =parent::prepare($query$types$result_types$lobs);
  822.             return $obj;
  823.         }
  824.         $is_manip ($result_types === MDB2_PREPARE_MANIP);
  825.         $offset $this->offset;
  826.         $limit $this->limit;
  827.         $this->offset $this->limit = 0;
  828.         $query $this->_modifyQuery($query$is_manip$limit$offset);
  829.         $result $this->debug($query__FUNCTION__array('is_manip' => $is_manip'when' => 'pre'));
  830.         if ($result{
  831.             if (PEAR::isError($result)) {
  832.                 return $result;
  833.             }
  834.             $query $result;
  835.         }
  836.         $placeholder_type_guess $placeholder_type = null;
  837.         $question '?';
  838.         $colon ':';
  839.         $positions = array();
  840.         $position = 0;
  841.         while ($position strlen($query)) {
  842.             $q_position strpos($query$question$position);
  843.             $c_position strpos($query$colon$position);
  844.             if ($q_position && $c_position{
  845.                 $p_position min($q_position$c_position);
  846.             elseif ($q_position{
  847.                 $p_position $q_position;
  848.             elseif ($c_position{
  849.                 $p_position $c_position;
  850.             else {
  851.                 break;
  852.             }
  853.             if (is_null($placeholder_type)) {
  854.                 $placeholder_type_guess $query[$p_position];
  855.             }
  856.             
  857.             $new_pos $this->_skipDelimitedStrings($query$position$p_position);
  858.             if (PEAR::isError($new_pos)) {
  859.                 return $new_pos;
  860.             }
  861.             if ($new_pos != $position{
  862.                 $position $new_pos;
  863.                 continue; //evaluate again starting from the new position
  864.             }
  865.             
  866.             if ($query[$position== $placeholder_type_guess{
  867.                 if (is_null($placeholder_type)) {
  868.                     $placeholder_type $query[$p_position];
  869.                     $question $colon $placeholder_type;
  870.                 }
  871.                 if ($placeholder_type == ':'{
  872.                     //make sure this is not part of an user defined variable
  873.                     $new_pos $this->_skipUserDefinedVariable($query$position);
  874.                     if ($new_pos != $position{
  875.                         $position $new_pos;
  876.                         continue; //evaluate again starting from the new position
  877.                     }
  878.                     $parameter preg_replace('/^.{'.($position+1).'}([a-z0-9_]+).*$/si''\\1'$query);
  879.                     if ($parameter === ''{
  880.                         $err =$this->raiseError(MDB2_ERROR_SYNTAXnullnull,
  881.                             'named parameter with an empty name'__FUNCTION__);
  882.                         return $err;
  883.                     }
  884.                     $positions[$p_position$parameter;
  885.                     $query substr_replace($query'?'$positionstrlen($parameter)+1);
  886.                 else {
  887.                     $positions[$p_positioncount($positions);
  888.                 }
  889.                 $position $p_position + 1;
  890.             else {
  891.                 $position $p_position;
  892.             }
  893.         }
  894.         $connection $this->getConnection();
  895.         if (PEAR::isError($connection)) {
  896.             return $connection;
  897.         }
  898.         $statement_name sprintf($this->options['statement_format']$this->phptypemd5(time(rand()));
  899.         $query = "PREPARE $statement_name FROM ".$this->quote($query'text');
  900.         $statement =$this->_doQuery($querytrue$connection);
  901.         if (PEAR::isError($statement)) {
  902.             return $statement;
  903.         }
  904.  
  905.         $class_name 'MDB2_Statement_'.$this->phptype;
  906.         $obj =new $class_name($this$statement_name$positions$query$types$result_types$is_manip$limit$offset);
  907.         $this->debug($query__FUNCTION__array('is_manip' => $is_manip'when' => 'post''result' => $obj));
  908.         return $obj;
  909.     }
  910.  
  911.     // }}}
  912.     // {{{ replace()
  913.  
  914.     /**
  915.      * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
  916.      * query, except that if there is already a row in the table with the same
  917.      * key field values, the REPLACE query just updates its values instead of
  918.      * inserting a new row.
  919.      *
  920.      * The REPLACE type of query does not make part of the SQL standards. Since
  921.      * practically only MySQL implements it natively, this type of query is
  922.      * emulated through this method for other DBMS using standard types of
  923.      * queries inside a transaction to assure the atomicity of the operation.
  924.      *
  925.      * @access public
  926.      *
  927.      * @param string $table name of the table on which the REPLACE query will
  928.      *   be executed.
  929.      * @param array $fields associative array that describes the fields and the
  930.      *   values that will be inserted or updated in the specified table. The
  931.      *   indexes of the array are the names of all the fields of the table. The
  932.      *   values of the array are also associative arrays that describe the
  933.      *   values and other properties of the table fields.
  934.      *
  935.      *   Here follows a list of field properties that need to be specified:
  936.      *
  937.      *     value:
  938.      *           Value to be assigned to the specified field. This value may be
  939.      *           of specified in database independent type format as this
  940.      *           function can perform the necessary datatype conversions.
  941.      *
  942.      *     Default:
  943.      *           this property is required unless the Null property
  944.      *           is set to 1.
  945.      *
  946.      *     type
  947.      *           Name of the type of the field. Currently, all types Metabase
  948.      *           are supported except for clob and blob.
  949.      *
  950.      *     Default: no type conversion
  951.      *
  952.      *     null
  953.      *           Boolean property that indicates that the value for this field
  954.      *           should be set to null.
  955.      *
  956.      *           The default value for fields missing in INSERT queries may be
  957.      *           specified the definition of a table. Often, the default value
  958.      *           is already null, but since the REPLACE may be emulated using
  959.      *           an UPDATE query, make sure that all fields of the table are
  960.      *           listed in this function argument array.
  961.      *
  962.      *     Default: 0
  963.      *
  964.      *     key
  965.      *           Boolean property that indicates that this field should be
  966.      *           handled as a primary key or at least as part of the compound
  967.      *           unique index of the table that will determine the row that will
  968.      *           updated if it exists or inserted a new row otherwise.
  969.      *
  970.      *           This function will fail if no key field is specified or if the
  971.      *           value of a key field is set to null because fields that are
  972.      *           part of unique index they may not be null.
  973.      *
  974.      *     Default: 0
  975.      *
  976.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  977.      */
  978.     function replace($table$fields)
  979.     {
  980.         $count count($fields);
  981.         $query $values '';
  982.         $keys $colnum = 0;
  983.         for (reset($fields)$colnum $countnext($fields)$colnum++{
  984.             $name key($fields);
  985.             if ($colnum > 0{
  986.                 $query .= ',';
  987.                 $values.= ',';
  988.             }
  989.             $query.= $name;
  990.             if (isset($fields[$name]['null']&& $fields[$name]['null']{
  991.                 $value 'NULL';
  992.             else {
  993.                 $type = isset($fields[$name]['type']$fields[$name]['type': null;
  994.                 $value $this->quote($fields[$name]['value']$type);
  995.             }
  996.             $values.= $value;
  997.             if (isset($fields[$name]['key']&& $fields[$name]['key']{
  998.                 if ($value === 'NULL'{
  999.                     return $this->raiseError(MDB2_ERROR_CANNOT_REPLACEnullnull,
  1000.                         'key value '.$name.' may not be NULL'__FUNCTION__);
  1001.                 }
  1002.                 $keys++;
  1003.             }
  1004.         }
  1005.         if ($keys == 0{
  1006.             return $this->raiseError(MDB2_ERROR_CANNOT_REPLACEnullnull,
  1007.                 'not specified which fields are keys'__FUNCTION__);
  1008.         }
  1009.  
  1010.         $connection $this->getConnection();
  1011.         if (PEAR::isError($connection)) {
  1012.             return $connection;
  1013.         }
  1014.  
  1015.         $query = "REPLACE INTO $table ($query) VALUES ($values)";
  1016.         $result =$this->_doQuery($querytrue$connection);
  1017.         if (PEAR::isError($result)) {
  1018.             return $result;
  1019.         }
  1020.         return $this->_affectedRows($connection$result);
  1021.     }
  1022.  
  1023.     // }}}
  1024.     // {{{ nextID()
  1025.  
  1026.     /**
  1027.      * Returns the next free id of a sequence
  1028.      *
  1029.      * @param string $seq_name name of the sequence
  1030.      * @param boolean $ondemand when true the sequence is
  1031.      *                           automatic created, if it
  1032.      *                           not exists
  1033.      *
  1034.      * @return mixed MDB2 Error Object or id
  1035.      * @access public
  1036.      */
  1037.     function nextID($seq_name$ondemand = true)
  1038.     {
  1039.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  1040.         $seqcol_name $this->quoteIdentifier($this->options['seqcol_name']true);
  1041.         $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
  1042.         $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  1043.         $result =$this->_doQuery($querytrue);
  1044.         $this->popExpect();
  1045.         if (PEAR::isError($result)) {
  1046.             if ($ondemand && $result->getCode(== MDB2_ERROR_NOSUCHTABLE{
  1047.                 $this->loadModule('Manager'nulltrue);
  1048.                 $result $this->manager->createSequence($seq_name);
  1049.                 if (PEAR::isError($result)) {
  1050.                     return $this->raiseError($resultnullnull,
  1051.                         'on demand sequence '.$seq_name.' could not be created'__FUNCTION__);
  1052.                 else {
  1053.                     return $this->nextID($seq_namefalse);
  1054.                 }
  1055.             }
  1056.             return $result;
  1057.         }
  1058.         $value $this->lastInsertID();
  1059.         if (is_numeric($value)) {
  1060.             $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
  1061.             $result =$this->_doQuery($querytrue);
  1062.             if (PEAR::isError($result)) {
  1063.                 $this->warnings['nextID: could not delete previous sequence table values from '.$seq_name;
  1064.             }
  1065.         }
  1066.         return $value;
  1067.     }
  1068.  
  1069.     // }}}
  1070.     // {{{ lastInsertID()
  1071.  
  1072.     /**
  1073.      * Returns the autoincrement ID if supported or $id or fetches the current
  1074.      * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
  1075.      *
  1076.      * @param string $table name of the table into which a new row was inserted
  1077.      * @param string $field name of the field into which a new row was inserted
  1078.      * @return mixed MDB2 Error Object or id
  1079.      * @access public
  1080.      */
  1081.     function lastInsertID($table = null$field = null)
  1082.     {
  1083.         // not using mysql_insert_id() due to http://pear.php.net/bugs/bug.php?id=8051
  1084.         return $this->queryOne('SELECT LAST_INSERT_ID()''integer');
  1085.     }
  1086.  
  1087.     // }}}
  1088.     // {{{ currID()
  1089.  
  1090.     /**
  1091.      * Returns the current id of a sequence
  1092.      *
  1093.      * @param string $seq_name name of the sequence
  1094.      * @return mixed MDB2 Error Object or id
  1095.      * @access public
  1096.      */
  1097.     function currID($seq_name)
  1098.     {
  1099.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  1100.         $seqcol_name $this->quoteIdentifier($this->options['seqcol_name']true);
  1101.         $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
  1102.         return $this->queryOne($query'integer');
  1103.     }
  1104. }
  1105.  
  1106. /**
  1107.  * MDB2 MySQL result driver
  1108.  *
  1109.  * @package MDB2
  1110.  * @category Database
  1111.  * @author  Lukas Smith <smith@pooteeweet.org>
  1112.  */
  1113. class MDB2_Result_mysql extends MDB2_Result_Common
  1114. {
  1115.     // }}}
  1116.     // {{{ fetchRow()
  1117.  
  1118.     /**
  1119.      * Fetch a row and insert the data into an existing array.
  1120.      *
  1121.      * @param int       $fetchmode  how the array data should be indexed
  1122.      * @param int    $rownum    number of the row where the data can be found
  1123.      * @return int data array on success, a MDB2 error on failure
  1124.      * @access public
  1125.      */
  1126.     function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT$rownum = null)
  1127.     {
  1128.         if (!is_null($rownum)) {
  1129.             $seek $this->seek($rownum);
  1130.             if (PEAR::isError($seek)) {
  1131.                 return $seek;
  1132.             }
  1133.         }
  1134.         if ($fetchmode == MDB2_FETCHMODE_DEFAULT{
  1135.             $fetchmode $this->db->fetchmode;
  1136.         }
  1137.         if ($fetchmode MDB2_FETCHMODE_ASSOC{
  1138.             $row @mysql_fetch_assoc($this->result);
  1139.             if (is_array($row)
  1140.                 && $this->db->options['portability'MDB2_PORTABILITY_FIX_CASE
  1141.             {
  1142.                 $row array_change_key_case($row$this->db->options['field_case']);
  1143.             }
  1144.         else {
  1145.            $row @mysql_fetch_row($this->result);
  1146.         }
  1147.  
  1148.         if (!$row{
  1149.             if ($this->result === false{
  1150.                 $err =$this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1151.                     'resultset has already been freed'__FUNCTION__);
  1152.                 return $err;
  1153.             }
  1154.             $null = null;
  1155.             return $null;
  1156.         }
  1157.         $mode $this->db->options['portability'MDB2_PORTABILITY_EMPTY_TO_NULL;
  1158.         if ($mode{
  1159.             $this->db->_fixResultArrayValues($row$mode);
  1160.         }
  1161.         if (!empty($this->types)) {
  1162.             $row $this->db->datatype->convertResultRow($this->types$rowfalse);
  1163.         }
  1164.         if (!empty($this->values)) {
  1165.             $this->_assignBindColumns($row);
  1166.         }
  1167.         if ($fetchmode === MDB2_FETCHMODE_OBJECT{
  1168.             $object_class $this->db->options['fetch_class'];
  1169.             if ($object_class == 'stdClass'{
  1170.                 $row = (object) $row;
  1171.             else {
  1172.                 $row &new $object_class($row);
  1173.             }
  1174.         }
  1175.         ++$this->rownum;
  1176.         return $row;
  1177.     }
  1178.  
  1179.     // }}}
  1180.     // {{{ _getColumnNames()
  1181.  
  1182.     /**
  1183.      * Retrieve the names of columns returned by the DBMS in a query result.
  1184.      *
  1185.      * @return  mixed   Array variable that holds the names of columns as keys
  1186.      *                   or an MDB2 error on failure.
  1187.      *                   Some DBMS may not return any columns when the result set
  1188.      *                   does not contain any rows.
  1189.      * @access private
  1190.      */
  1191.     function _getColumnNames()
  1192.     {
  1193.         $columns = array();
  1194.         $numcols $this->numCols();
  1195.         if (PEAR::isError($numcols)) {
  1196.             return $numcols;
  1197.         }
  1198.         for ($column = 0; $column $numcols$column++{
  1199.             $column_name @mysql_field_name($this->result$column);
  1200.             $columns[$column_name$column;
  1201.         }
  1202.         if ($this->db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  1203.             $columns array_change_key_case($columns$this->db->options['field_case']);
  1204.         }
  1205.         return $columns;
  1206.     }
  1207.  
  1208.     // }}}
  1209.     // {{{ numCols()
  1210.  
  1211.     /**
  1212.      * Count the number of columns returned by the DBMS in a query result.
  1213.      *
  1214.      * @return mixed integer value with the number of columns, a MDB2 error
  1215.      *                        on failure
  1216.      * @access public
  1217.      */
  1218.     function numCols()
  1219.     {
  1220.         $cols @mysql_num_fields($this->result);
  1221.         if (is_null($cols)) {
  1222.             if ($this->result === false{
  1223.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1224.                     'resultset has already been freed'__FUNCTION__);
  1225.             elseif (is_null($this->result)) {
  1226.                 return count($this->types);
  1227.             }
  1228.             return $this->db->raiseError(nullnullnull,
  1229.                 'Could not get column count'__FUNCTION__);
  1230.         }
  1231.         return $cols;
  1232.     }
  1233.  
  1234.     // }}}
  1235.     // {{{ free()
  1236.  
  1237.     /**
  1238.      * Free the internal resources associated with result.
  1239.      *
  1240.      * @return boolean true on success, false if result is invalid
  1241.      * @access public
  1242.      */
  1243.     function free()
  1244.     {
  1245.         if (is_resource($this->result&& $this->db->connection{
  1246.             $free @mysql_free_result($this->result);
  1247.             if ($free === false{
  1248.                 return $this->db->raiseError(nullnullnull,
  1249.                     'Could not free result'__FUNCTION__);
  1250.             }
  1251.         }
  1252.         $this->result = false;
  1253.         return MDB2_OK;
  1254.     }
  1255. }
  1256.  
  1257. /**
  1258.  * MDB2 MySQL buffered result driver
  1259.  *
  1260.  * @package MDB2
  1261.  * @category Database
  1262.  * @author  Lukas Smith <smith@pooteeweet.org>
  1263.  */
  1264. {
  1265.     // }}}
  1266.     // {{{ seek()
  1267.  
  1268.     /**
  1269.      * Seek to a specific row in a result set
  1270.      *
  1271.      * @param int    $rownum    number of the row where the data can be found
  1272.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1273.      * @access public
  1274.      */
  1275.     function seek($rownum = 0)
  1276.     {
  1277.         if ($this->rownum != ($rownum - 1&& !@mysql_data_seek($this->result$rownum)) {
  1278.             if ($this->result === false{
  1279.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1280.                     'resultset has already been freed'__FUNCTION__);
  1281.             elseif (is_null($this->result)) {
  1282.                 return MDB2_OK;
  1283.             }
  1284.             return $this->db->raiseError(MDB2_ERROR_INVALIDnullnull,
  1285.                 'tried to seek to an invalid row number ('.$rownum.')'__FUNCTION__);
  1286.         }
  1287.         $this->rownum $rownum - 1;
  1288.         return MDB2_OK;
  1289.     }
  1290.  
  1291.     // }}}
  1292.     // {{{ valid()
  1293.  
  1294.     /**
  1295.      * Check if the end of the result set has been reached
  1296.      *
  1297.      * @return mixed true or false on sucess, a MDB2 error on failure
  1298.      * @access public
  1299.      */
  1300.     function valid()
  1301.     {
  1302.         $numrows $this->numRows();
  1303.         if (PEAR::isError($numrows)) {
  1304.             return $numrows;
  1305.         }
  1306.         return $this->rownum ($numrows - 1);
  1307.     }
  1308.  
  1309.     // }}}
  1310.     // {{{ numRows()
  1311.  
  1312.     /**
  1313.      * Returns the number of rows in a result object
  1314.      *
  1315.      * @return mixed MDB2 Error Object or the number of rows
  1316.      * @access public
  1317.      */
  1318.     function numRows()
  1319.     {
  1320.         $rows @mysql_num_rows($this->result);
  1321.         if (is_null($rows)) {
  1322.             if ($this->result === false{
  1323.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1324.                     'resultset has already been freed'__FUNCTION__);
  1325.             elseif (is_null($this->result)) {
  1326.                 return 0;
  1327.             }
  1328.             return $this->db->raiseError(nullnullnull,
  1329.                 'Could not get row count'__FUNCTION__);
  1330.         }
  1331.         return $rows;
  1332.     }
  1333. }
  1334.  
  1335. /**
  1336.  * MDB2 MySQL statement driver
  1337.  *
  1338.  * @package MDB2
  1339.  * @category Database
  1340.  * @author  Lukas Smith <smith@pooteeweet.org>
  1341.  */
  1342. class MDB2_Statement_mysql extends MDB2_Statement_Common
  1343. {
  1344.     // {{{ _execute()
  1345.  
  1346.     /**
  1347.      * Execute a prepared query statement helper method.
  1348.      *
  1349.      * @param mixed $result_class string which specifies which result class to use
  1350.      * @param mixed $result_wrap_class string which specifies which class to wrap results in
  1351.      * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
  1352.      * @access private
  1353.      */
  1354.     function &_execute($result_class = true$result_wrap_class = false)
  1355.     {
  1356.         if (is_null($this->statement)) {
  1357.             $result =parent::_execute($result_class$result_wrap_class);
  1358.             return $result;
  1359.         }
  1360.         $this->db->last_query = $this->query;
  1361.         $this->db->debug($this->query'execute'array('is_manip' => $this->is_manip'when' => 'pre''parameters' => $this->values));
  1362.         if ($this->db->getOption('disable_query')) {
  1363.             $result $this->is_manip ? 0 : null;
  1364.             return $result;
  1365.         }
  1366.  
  1367.         $connection $this->db->getConnection();
  1368.         if (PEAR::isError($connection)) {
  1369.             return $connection;
  1370.         }
  1371.  
  1372.         $query 'EXECUTE '.$this->statement;
  1373.         if (!empty($this->positions)) {
  1374.             $parameters = array();
  1375.             foreach ($this->positions as $parameter{
  1376.                 if (!array_key_exists($parameter$this->values)) {
  1377.                     return $this->db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  1378.                         'Unable to bind to missing placeholder: '.$parameter__FUNCTION__);
  1379.                 }
  1380.                 $value $this->values[$parameter];
  1381.                 $type array_key_exists($parameter$this->types$this->types[$parameter: null;
  1382.                 if (is_resource($value|| $type == 'clob' || $type == 'blob'{
  1383.                     if (!is_resource($value&& preg_match('/^(\w+:\/\/)(.*)$/'$value$match)) {
  1384.                         if ($match[1== 'file://'{
  1385.                             $value $match[2];
  1386.                         }
  1387.                         $value @fopen($value'r');
  1388.                         $close = true;
  1389.                     }
  1390.                     if (is_resource($value)) {
  1391.                         $data '';
  1392.                         while (!@feof($value)) {
  1393.                             $data.= @fread($value$this->db->options['lob_buffer_length']);
  1394.                         }
  1395.                         if ($close{
  1396.                             @fclose($value);
  1397.                         }
  1398.                         $value $data;
  1399.                     }
  1400.                 }
  1401.                 $quoted $this->db->quote($value$type);
  1402.                 if (PEAR::isError($quoted)) {
  1403.                     return $quoted;
  1404.                 }
  1405.                 $param_query 'SET @'.$parameter.' = '.$quoted;
  1406.                 $result $this->db->_doQuery($param_querytrue$connection);
  1407.                 if (PEAR::isError($result)) {
  1408.                     return $result;
  1409.                 }
  1410.             }
  1411.             $query.= ' USING @'.implode(', @'array_values($this->positions));
  1412.         }
  1413.  
  1414.         $result $this->db->_doQuery($query$this->is_manip$connection);
  1415.         if (PEAR::isError($result)) {
  1416.             return $result;
  1417.         }
  1418.  
  1419.         if ($this->is_manip{
  1420.             $affected_rows $this->db->_affectedRows($connection$result);
  1421.             return $affected_rows;
  1422.         }
  1423.  
  1424.         $result =$this->db->_wrapResult($result$this->result_types,
  1425.             $result_class$result_wrap_class$this->limit$this->offset);
  1426.         $this->db->debug($this->query'execute'array('is_manip' => $this->is_manip'when' => 'post''result' => $result));
  1427.         return $result;
  1428.     }
  1429.  
  1430.     // }}}
  1431.     // {{{ free()
  1432.  
  1433.     /**
  1434.      * Release resources allocated for the specified prepared query.
  1435.      *
  1436.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1437.      * @access public
  1438.      */
  1439.     function free()
  1440.     {
  1441.         if (is_null($this->positions)) {
  1442.             return $this->db->raiseError(MDB2_ERRORnullnull,
  1443.                 'Prepared statement has already been freed'__FUNCTION__);
  1444.         }
  1445.         $result = MDB2_OK;
  1446.  
  1447.         if (!is_null($this->statement)) {
  1448.             $connection $this->db->getConnection();
  1449.             if (PEAR::isError($connection)) {
  1450.                 return $connection;
  1451.             }
  1452.             $query 'DEALLOCATE PREPARE '.$this->statement;
  1453.             $result $this->db->_doQuery($querytrue$connection);
  1454.         }
  1455.  
  1456.         parent::free();
  1457.         return $result;
  1458.     }
  1459. }
  1460. ?>

Documentation generated on Mon, 11 Mar 2019 14:57:27 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.