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

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