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

Source for file mysqli.php

Documentation is available at mysqli.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: mysqli.php,v 1.176 2007/11/10 13:27:03 quipo Exp $
  47. //
  48.  
  49. /**
  50.  * MDB2 MySQLi driver
  51.  *
  52.  * @package MDB2
  53.  * @category Database
  54.  * @author  Lukas Smith <smith@pooteeweet.org>
  55.  */
  56. class MDB2_Driver_mysqli extends MDB2_Driver_Common
  57. {
  58.     // {{{ properties
  59.  
  60.     var $string_quoting = array('start' => "'"'end' => "'"'escape' => '\\''escape_pattern' => '\\');
  61.  
  62.     var $identifier_quoting = array('start' => '`''end' => '`''escape' => '`');
  63.  
  64.     var $sql_comments = array(
  65.         array('start' => '-- ''end' => "\n"'escape' => false),
  66.         array('start' => '#''end' => "\n"'escape' => false),
  67.         array('start' => '/*''end' => '*/''escape' => false),
  68.     );
  69.  
  70.     var $server_capabilities_checked = false;
  71.  
  72.     var $start_transaction = false;
  73.  
  74.     var $varchar_max_length = 255;
  75.  
  76.     // }}}
  77.     // {{{ constructor
  78.  
  79.     /**
  80.      * Constructor
  81.      */
  82.     function __construct()
  83.     {
  84.         parent::__construct();
  85.  
  86.         $this->phptype 'mysqli';
  87.         $this->dbsyntax 'mysql';
  88.  
  89.         $this->supported['sequences''emulated';
  90.         $this->supported['indexes'= true;
  91.         $this->supported['affected_rows'= true;
  92.         $this->supported['transactions'= false;
  93.         $this->supported['savepoints'= false;
  94.         $this->supported['summary_functions'= true;
  95.         $this->supported['order_by_text'= true;
  96.         $this->supported['current_id''emulated';
  97.         $this->supported['limit_queries'= true;
  98.         $this->supported['LOBs'= true;
  99.         $this->supported['replace'= true;
  100.         $this->supported['sub_selects''emulated';
  101.         $this->supported['auto_increment'= true;
  102.         $this->supported['primary_key'= true;
  103.         $this->supported['result_introspection'= true;
  104.         $this->supported['prepared_statements''emulated';
  105.         $this->supported['identifier_quoting'= true;
  106.         $this->supported['pattern_escaping'= true;
  107.         $this->supported['new_link'= true;
  108.  
  109.         $this->options['default_table_type''';
  110.         $this->options['multi_query'= false;
  111.     }
  112.  
  113.     // }}}
  114.     // {{{ errorInfo()
  115.  
  116.     /**
  117.      * This method is used to collect information about an error
  118.      *
  119.      * @param integer $error 
  120.      * @return array 
  121.      * @access public
  122.      */
  123.     function errorInfo($error = null)
  124.     {
  125.         if ($this->connection{
  126.             $native_code @mysqli_errno($this->connection);
  127.             $native_msg  @mysqli_error($this->connection);
  128.         else {
  129.             $native_code @mysqli_connect_errno();
  130.             $native_msg  @mysqli_connect_error();
  131.         }
  132.         if (is_null($error)) {
  133.             static $ecode_map;
  134.             if (empty($ecode_map)) {
  135.                 $ecode_map = array(
  136.                     1000 => MDB2_ERROR_INVALID//hashchk
  137.                     1001 => MDB2_ERROR_INVALID//isamchk
  138.                     1004 => MDB2_ERROR_CANNOT_CREATE,
  139.                     1005 => MDB2_ERROR_CANNOT_CREATE,
  140.                     1006 => MDB2_ERROR_CANNOT_CREATE,
  141.                     1007 => MDB2_ERROR_ALREADY_EXISTS,
  142.                     1008 => MDB2_ERROR_CANNOT_DROP,
  143.                     1009 => MDB2_ERROR_CANNOT_DROP,
  144.                     1010 => MDB2_ERROR_CANNOT_DROP,
  145.                     1011 => MDB2_ERROR_CANNOT_DELETE,
  146.                     1022 => MDB2_ERROR_ALREADY_EXISTS,
  147.                     1029 => MDB2_ERROR_NOT_FOUND,
  148.                     1032 => MDB2_ERROR_NOT_FOUND,
  149.                     1044 => MDB2_ERROR_ACCESS_VIOLATION,
  150.                     1045 => MDB2_ERROR_ACCESS_VIOLATION,
  151.                     1046 => MDB2_ERROR_NODBSELECTED,
  152.                     1048 => MDB2_ERROR_CONSTRAINT,
  153.                     1049 => MDB2_ERROR_NOSUCHDB,
  154.                     1050 => MDB2_ERROR_ALREADY_EXISTS,
  155.                     1051 => MDB2_ERROR_NOSUCHTABLE,
  156.                     1054 => MDB2_ERROR_NOSUCHFIELD,
  157.                     1060 => MDB2_ERROR_ALREADY_EXISTS,
  158.                     1061 => MDB2_ERROR_ALREADY_EXISTS,
  159.                     1062 => MDB2_ERROR_ALREADY_EXISTS,
  160.                     1064 => MDB2_ERROR_SYNTAX,
  161.                     1067 => MDB2_ERROR_INVALID,
  162.                     1072 => MDB2_ERROR_NOT_FOUND,
  163.                     1086 => MDB2_ERROR_ALREADY_EXISTS,
  164.                     1091 => MDB2_ERROR_NOT_FOUND,
  165.                     1100 => MDB2_ERROR_NOT_LOCKED,
  166.                     1109 => MDB2_ERROR_NOT_FOUND,
  167.                     1125 => MDB2_ERROR_ALREADY_EXISTS,
  168.                     1136 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
  169.                     1138 => MDB2_ERROR_INVALID,
  170.                     1142 => MDB2_ERROR_ACCESS_VIOLATION,
  171.                     1143 => MDB2_ERROR_ACCESS_VIOLATION,
  172.                     1146 => MDB2_ERROR_NOSUCHTABLE,
  173.                     1149 => MDB2_ERROR_SYNTAX,
  174.                     1169 => MDB2_ERROR_CONSTRAINT,
  175.                     1176 => MDB2_ERROR_NOT_FOUND,
  176.                     1177 => MDB2_ERROR_NOSUCHTABLE,
  177.                     1213 => MDB2_ERROR_DEADLOCK,
  178.                     1216 => MDB2_ERROR_CONSTRAINT,
  179.                     1217 => MDB2_ERROR_CONSTRAINT,
  180.                     1227 => MDB2_ERROR_ACCESS_VIOLATION,
  181.                     1299 => MDB2_ERROR_INVALID_DATE,
  182.                     1300 => MDB2_ERROR_INVALID,
  183.                     1304 => MDB2_ERROR_ALREADY_EXISTS,
  184.                     1305 => MDB2_ERROR_NOT_FOUND,
  185.                     1306 => MDB2_ERROR_CANNOT_DROP,
  186.                     1307 => MDB2_ERROR_CANNOT_CREATE,
  187.                     1334 => MDB2_ERROR_CANNOT_ALTER,
  188.                     1339 => MDB2_ERROR_NOT_FOUND,
  189.                     1356 => MDB2_ERROR_INVALID,
  190.                     1359 => MDB2_ERROR_ALREADY_EXISTS,
  191.                     1360 => MDB2_ERROR_NOT_FOUND,
  192.                     1363 => MDB2_ERROR_NOT_FOUND,
  193.                     1365 => MDB2_ERROR_DIVZERO,
  194.                     1451 => MDB2_ERROR_CONSTRAINT,
  195.                     1452 => MDB2_ERROR_CONSTRAINT,
  196.                     1542 => MDB2_ERROR_CANNOT_DROP,
  197.                     1546 => MDB2_ERROR_CONSTRAINT,
  198.                     1582 => MDB2_ERROR_CONSTRAINT,
  199.                     2019 => MDB2_ERROR_INVALID,
  200.                 );
  201.             }
  202.             if ($this->options['portability'MDB2_PORTABILITY_ERRORS{
  203.                 $ecode_map[1022= MDB2_ERROR_CONSTRAINT;
  204.                 $ecode_map[1048= MDB2_ERROR_CONSTRAINT_NOT_NULL;
  205.                 $ecode_map[1062= MDB2_ERROR_CONSTRAINT;
  206.             else {
  207.                 // Doing this in case mode changes during runtime.
  208.                 $ecode_map[1022= MDB2_ERROR_ALREADY_EXISTS;
  209.                 $ecode_map[1048= MDB2_ERROR_CONSTRAINT;
  210.                 $ecode_map[1062= MDB2_ERROR_ALREADY_EXISTS;
  211.             }
  212.             if (isset($ecode_map[$native_code])) {
  213.                 $error $ecode_map[$native_code];
  214.             }
  215.         }
  216.         return array($error$native_code$native_msg);
  217.     }
  218.  
  219.     // }}}
  220.     // {{{ escape()
  221.  
  222.     /**
  223.      * Quotes a string so it can be safely used in a query. It will quote
  224.      * the text so it can safely be used within a query.
  225.      *
  226.      * @param   string  the input string to quote
  227.      * @param   bool    escape wildcards
  228.      *
  229.      * @return  string  quoted string
  230.      *
  231.      * @access  public
  232.      */
  233.     function escape($text$escape_wildcards = false)
  234.     {
  235.         if ($escape_wildcards{
  236.             $text $this->escapePattern($text);
  237.         }
  238.         $connection $this->getConnection();
  239.         if (PEAR::isError($connection)) {
  240.             return $connection;
  241.         }
  242.         $text @mysqli_real_escape_string($connection$text);
  243.         return $text;
  244.     }
  245.  
  246.     // }}}
  247.     // {{{ beginTransaction()
  248.  
  249.     /**
  250.      * Start a transaction or set a savepoint.
  251.      *
  252.      * @param   string  name of a savepoint to set
  253.      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
  254.      *
  255.      * @access  public
  256.      */
  257.     function beginTransaction($savepoint = null)
  258.     {
  259.         $this->debug('Starting transaction/savepoint'__FUNCTION__array('is_manip' => true'savepoint' => $savepoint));
  260.         $this->_getServerCapabilities();
  261.         if (!is_null($savepoint)) {
  262.             if (!$this->supports('savepoints')) {
  263.                 return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  264.                     'savepoints are not supported'__FUNCTION__);
  265.             }
  266.             if (!$this->in_transaction{
  267.                 return $this->raiseError(MDB2_ERROR_INVALIDnullnull,
  268.                     'savepoint cannot be released when changes are auto committed'__FUNCTION__);
  269.             }
  270.             $query 'SAVEPOINT '.$savepoint;
  271.             return $this->_doQuery($querytrue);
  272.         elseif ($this->in_transaction{
  273.             return MDB2_OK;  //nothing to do
  274.         }
  275.         $query $this->start_transaction ? 'START TRANSACTION' 'SET AUTOCOMMIT = 1';
  276.         $result =$this->_doQuery($querytrue);
  277.         if (PEAR::isError($result)) {
  278.             return $result;
  279.         }
  280.         $this->in_transaction = true;
  281.         return MDB2_OK;
  282.     }
  283.  
  284.     // }}}
  285.     // {{{ commit()
  286.  
  287.     /**
  288.      * Commit the database changes done during a transaction that is in
  289.      * progress or release a savepoint. This function may only be called when
  290.      * auto-committing is disabled, otherwise it will fail. Therefore, a new
  291.      * transaction is implicitly started after committing the pending changes.
  292.      *
  293.      * @param   string  name of a savepoint to release
  294.      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
  295.      *
  296.      * @access  public
  297.      */
  298.     function commit($savepoint = null)
  299.     {
  300.         $this->debug('Committing transaction/savepoint'__FUNCTION__array('is_manip' => true'savepoint' => $savepoint));
  301.         if (!$this->in_transaction{
  302.             return $this->raiseError(MDB2_ERROR_INVALIDnullnull,
  303.                 'commit/release savepoint cannot be done changes are auto committed'__FUNCTION__);
  304.         }
  305.         if (!is_null($savepoint)) {
  306.             if (!$this->supports('savepoints')) {
  307.                 return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  308.                     'savepoints are not supported'__FUNCTION__);
  309.             }
  310.             $server_info $this->getServerVersion();
  311.             if (version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch']'5.0.3''<')) {
  312.                 return MDB2_OK;
  313.             }
  314.             $query 'RELEASE SAVEPOINT '.$savepoint;
  315.             return $this->_doQuery($querytrue);
  316.         }
  317.  
  318.         if (!$this->supports('transactions')) {
  319.             return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  320.                 'transactions are not supported'__FUNCTION__);
  321.         }
  322.  
  323.         $result =$this->_doQuery('COMMIT'true);
  324.         if (PEAR::isError($result)) {
  325.             return $result;
  326.         }
  327.         if (!$this->start_transaction{
  328.             $query 'SET AUTOCOMMIT = 0';
  329.             $result =$this->_doQuery($querytrue);
  330.             if (PEAR::isError($result)) {
  331.                 return $result;
  332.             }
  333.         }
  334.         $this->in_transaction = false;
  335.         return MDB2_OK;
  336.     }
  337.  
  338.     // }}}
  339.     // {{{ rollback()
  340.  
  341.     /**
  342.      * Cancel any database changes done during a transaction or since a specific
  343.      * savepoint that is in progress. This function may only be called when
  344.      * auto-committing is disabled, otherwise it will fail. Therefore, a new
  345.      * transaction is implicitly started after canceling the pending changes.
  346.      *
  347.      * @param   string  name of a savepoint to rollback to
  348.      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
  349.      *
  350.      * @access  public
  351.      */
  352.     function rollback($savepoint = null)
  353.     {
  354.         $this->debug('Rolling back transaction/savepoint'__FUNCTION__array('is_manip' => true'savepoint' => $savepoint));
  355.         if (!$this->in_transaction{
  356.             return $this->raiseError(MDB2_ERROR_INVALIDnullnull,
  357.                 'rollback cannot be done changes are auto committed'__FUNCTION__);
  358.         }
  359.         if (!is_null($savepoint)) {
  360.             if (!$this->supports('savepoints')) {
  361.                 return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  362.                     'savepoints are not supported'__FUNCTION__);
  363.             }
  364.             $query 'ROLLBACK TO SAVEPOINT '.$savepoint;
  365.             return $this->_doQuery($querytrue);
  366.         }
  367.  
  368.         $query 'ROLLBACK';
  369.         $result =$this->_doQuery($querytrue);
  370.         if (PEAR::isError($result)) {
  371.             return $result;
  372.         }
  373.         if (!$this->start_transaction{
  374.             $query 'SET AUTOCOMMIT = 0';
  375.             $result =$this->_doQuery($querytrue);
  376.             if (PEAR::isError($result)) {
  377.                 return $result;
  378.             }
  379.         }
  380.         $this->in_transaction = false;
  381.         return MDB2_OK;
  382.     }
  383.  
  384.     // }}}
  385.     // {{{ function setTransactionIsolation()
  386.  
  387.     /**
  388.      * Set the transacton isolation level.
  389.      *
  390.      * @param   string  standard isolation level
  391.      *                   READ UNCOMMITTED (allows dirty reads)
  392.      *                   READ COMMITTED (prevents dirty reads)
  393.      *                   REPEATABLE READ (prevents nonrepeatable reads)
  394.      *                   SERIALIZABLE (prevents phantom reads)
  395.      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
  396.      *
  397.      * @access  public
  398.      * @since   2.1.1
  399.      */
  400.     function setTransactionIsolation($isolation)
  401.     {
  402.         $this->debug('Setting transaction isolation level'__FUNCTION__array('is_manip' => true));
  403.         if (!$this->supports('transactions')) {
  404.             return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  405.                 'transactions are not supported'__FUNCTION__);
  406.         }
  407.         switch ($isolation{
  408.         case 'READ UNCOMMITTED':
  409.         case 'READ COMMITTED':
  410.         case 'REPEATABLE READ':
  411.         case 'SERIALIZABLE':
  412.             break;
  413.         default:
  414.             return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  415.                 'isolation level is not supported: '.$isolation__FUNCTION__);
  416.         }
  417.  
  418.         $query = "SET SESSION TRANSACTION ISOLATION LEVEL $isolation";
  419.         return $this->_doQuery($querytrue);
  420.     }
  421.  
  422.     // }}}
  423.     // {{{ connect()
  424.  
  425.     /**
  426.      * Connect to the database
  427.      *
  428.      * @return true on success, MDB2 Error Object on failure
  429.      */
  430.     function connect()
  431.     {
  432.         if (is_object($this->connection)) {
  433.             //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0) {
  434.             if (MDB2::areEquals($this->connected_dsn$this->dsn)) {
  435.                 return MDB2_OK;
  436.             }
  437.             $this->connection = 0;
  438.         }
  439.  
  440.         if (!PEAR::loadExtension($this->phptype)) {
  441.             return $this->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  442.                 'extension '.$this->phptype.' is not compiled into PHP'__FUNCTION__);
  443.         }
  444.  
  445.         $connection @mysqli_init();
  446.         if (!empty($this->dsn['charset']&& defined('MYSQLI_SET_CHARSET_NAME')) {
  447.             @mysqli_options($connectionMYSQLI_SET_CHARSET_NAME$this->dsn['charset']);
  448.         }
  449.  
  450.  
  451.         if ($this->options['ssl']{
  452.             @mysqli_ssl_set(
  453.                 $connection,
  454.                 empty($this->dsn['key'])    ? null : $this->dsn['key'],
  455.                 empty($this->dsn['cert'])   ? null : $this->dsn['cert'],
  456.                 empty($this->dsn['ca'])     ? null : $this->dsn['ca'],
  457.                 empty($this->dsn['capath']? null : $this->dsn['capath'],
  458.                 empty($this->dsn['cipher']? null : $this->dsn['cipher']
  459.             );
  460.         }
  461.  
  462.         if (!@mysqli_real_connect(
  463.             $connection,
  464.             $this->dsn['hostspec'],
  465.             $this->dsn['username'],
  466.             $this->dsn['password'],
  467.             $this->database_name,
  468.             $this->dsn['port'],
  469.             $this->dsn['socket']
  470.         )) {
  471.  
  472.             if (($err @mysqli_connect_error()) != ''{
  473.                 return $this->raiseError(null,
  474.                     nullnull$err__FUNCTION__);
  475.             else {
  476.                 return $this->raiseError(MDB2_ERROR_CONNECT_FAILEDnullnull,
  477.                     'unable to establish a connection'__FUNCTION__);
  478.             }
  479.         }
  480.  
  481.         if (!empty($this->dsn['charset']&& !defined('MYSQLI_SET_CHARSET_NAME')) {
  482.             $result $this->setCharset($this->dsn['charset']$connection);
  483.             if (PEAR::isError($result)) {
  484.                 return $result;
  485.             }
  486.         }
  487.  
  488.         $this->connection $connection;
  489.         $this->connected_dsn $this->dsn;
  490.         $this->connected_database_name $this->database_name;
  491.         $this->dbsyntax $this->dsn['dbsyntax'$this->dsn['dbsyntax'$this->phptype;
  492.  
  493.         $this->supported['transactions'$this->options['use_transactions'];
  494.         if ($this->options['default_table_type']{
  495.             switch (strtoupper($this->options['default_table_type'])) {
  496.             case 'BLACKHOLE':
  497.             case 'MEMORY':
  498.             case 'ARCHIVE':
  499.             case 'CSV':
  500.             case 'HEAP':
  501.             case 'ISAM':
  502.             case 'MERGE':
  503.             case 'MRG_ISAM':
  504.             case 'ISAM':
  505.             case 'MRG_MYISAM':
  506.             case 'MYISAM':
  507.                 $this->supported['transactions'= false;
  508.                 $this->warnings[$this->options['default_table_type'.
  509.                     ' is not a supported default table type';
  510.                 break;
  511.             }
  512.         }
  513.         
  514.         $this->_getServerCapabilities();
  515.  
  516.         return MDB2_OK;
  517.     }
  518.  
  519.     // }}}
  520.     // {{{ setCharset()
  521.  
  522.     /**
  523.      * Set the charset on the current connection
  524.      *
  525.      * @param string    charset
  526.      * @param resource  connection handle
  527.      *
  528.      * @return true on success, MDB2 Error Object on failure
  529.      */
  530.     function setCharset($charset$connection = null)
  531.     {
  532.         if (is_null($connection)) {
  533.             $connection $this->getConnection();
  534.             if (PEAR::isError($connection)) {
  535.                 return $connection;
  536.             }
  537.         }
  538.         $client_info mysqli_get_client_version();
  539.         if (OS_WINDOWS && ((40111 > $client_info||
  540.             ((50000 <= $client_info&& (50006 > $client_info)))
  541.         {
  542.             $query "SET NAMES '".mysqli_real_escape_string($connection$charset)."'";
  543.             return $this->_doQuery($querytrue$connection);
  544.         }
  545.         if (!$result mysqli_set_charset($connection$charset)) {
  546.             $err =$this->raiseError(nullnullnull,
  547.                 'Could not set client character set'__FUNCTION__);
  548.             return $err;
  549.         }
  550.         return $result;
  551.     }
  552.  
  553.     // }}}
  554.     // {{{ disconnect()
  555.  
  556.     /**
  557.      * Log out and disconnect from the database.
  558.      *
  559.      * @param  boolean $force if the disconnect should be forced even if the
  560.      *                         connection is opened persistently
  561.      * @return mixed true on success, false if not connected and error
  562.      *                 object on error
  563.      * @access public
  564.      */
  565.     function disconnect($force = true)
  566.     {
  567.         if (is_object($this->connection)) {
  568.             if ($this->in_transaction{
  569.                 $dsn $this->dsn;
  570.                 $database_name $this->database_name;
  571.                 $persistent $this->options['persistent'];
  572.                 $this->dsn $this->connected_dsn;
  573.                 $this->database_name $this->connected_database_name;
  574.                 $this->options['persistent'$this->opened_persistent;
  575.                 $this->rollback();
  576.                 $this->dsn $dsn;
  577.                 $this->database_name $database_name;
  578.                 $this->options['persistent'$persistent;
  579.             }
  580.  
  581.             if ($force{
  582.                 @mysqli_close($this->connection);
  583.             }
  584.         }
  585.         return parent::disconnect($force);
  586.     }
  587.  
  588.     // }}}
  589.     // {{{ _doQuery()
  590.  
  591.     /**
  592.      * Execute a query
  593.      * @param string $query  query
  594.      * @param boolean $is_manip  if the query is a manipulation query
  595.      * @param resource $connection 
  596.      * @param string $database_name 
  597.      * @return result or error object
  598.      * @access protected
  599.      */
  600.     function &_doQuery($query$is_manip = false$connection = null$database_name = null)
  601.     {
  602.         $this->last_query $query;
  603.         $result $this->debug($query'query'array('is_manip' => $is_manip'when' => 'pre'));
  604.         if ($result{
  605.             if (PEAR::isError($result)) {
  606.                 return $result;
  607.             }
  608.             $query $result;
  609.         }
  610.         if ($this->options['disable_query']{
  611.             $result $is_manip ? 0 : null;
  612.             return $result;
  613.         }
  614.  
  615.         if (is_null($connection)) {
  616.             $connection $this->getConnection();
  617.             if (PEAR::isError($connection)) {
  618.                 return $connection;
  619.             }
  620.         }
  621.         if (is_null($database_name)) {
  622.             $database_name $this->database_name;
  623.         }
  624.  
  625.         if ($database_name{
  626.             if ($database_name != $this->connected_database_name{
  627.                 if (!@mysqli_select_db($connection$database_name)) {
  628.                     $err $this->raiseError(nullnullnull,
  629.                         'Could not select the database: '.$database_name__FUNCTION__);
  630.                     return $err;
  631.                 }
  632.                 $this->connected_database_name $database_name;
  633.             }
  634.         }
  635.  
  636.         if ($this->options['multi_query']{
  637.             $result mysqli_multi_query($connection$query);
  638.         else {
  639.             $resultmode $this->options['result_buffering'? MYSQLI_USE_RESULT : MYSQLI_USE_RESULT;
  640.             $result mysqli_query($connection$query);
  641.         }
  642.  
  643.         if (!$result{
  644.             $err =$this->raiseError(nullnullnull,
  645.                 'Could not execute statement'__FUNCTION__);
  646.             return $err;
  647.         }
  648.  
  649.         if ($this->options['multi_query']{
  650.             if ($this->options['result_buffering']{
  651.                 if (!($result @mysqli_store_result($connection))) {
  652.                     $err =$this->raiseError(nullnullnull,
  653.                         'Could not get the first result from a multi query'__FUNCTION__);
  654.                     return $err;
  655.                 }
  656.             elseif (!($result @mysqli_use_result($connection))) {
  657.                 $err =$this->raiseError(nullnullnull,
  658.                         'Could not get the first result from a multi query'__FUNCTION__);
  659.                 return $err;
  660.             }
  661.         }
  662.  
  663.         $this->debug($query'query'array('is_manip' => $is_manip'when' => 'post''result' => $result));
  664.         return $result;
  665.     }
  666.  
  667.     // }}}
  668.     // {{{ _affectedRows()
  669.  
  670.     /**
  671.      * Returns the number of rows affected
  672.      *
  673.      * @param resource $result 
  674.      * @param resource $connection 
  675.      * @return mixed MDB2 Error Object or the number of rows affected
  676.      * @access private
  677.      */
  678.     function _affectedRows($connection$result = null)
  679.     {
  680.         if (is_null($connection)) {
  681.             $connection $this->getConnection();
  682.             if (PEAR::isError($connection)) {
  683.                 return $connection;
  684.             }
  685.         }
  686.         return @mysqli_affected_rows($connection);
  687.     }
  688.  
  689.     // }}}
  690.     // {{{ _modifyQuery()
  691.  
  692.     /**
  693.      * Changes a query string for various DBMS specific reasons
  694.      *
  695.      * @param string $query  query to modify
  696.      * @param boolean $is_manip  if it is a DML query
  697.      * @param integer $limit  limit the number of rows
  698.      * @param integer $offset  start reading from given offset
  699.      * @return string modified query
  700.      * @access protected
  701.      */
  702.     function _modifyQuery($query$is_manip$limit$offset)
  703.     {
  704.         if ($this->options['portability'MDB2_PORTABILITY_DELETE_COUNT{
  705.             // "DELETE FROM table" gives 0 affected rows in MySQL.
  706.             // This little hack lets you know how many rows were deleted.
  707.             if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i'$query)) {
  708.                 $query preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
  709.                                       'DELETE FROM \1 WHERE 1=1'$query);
  710.             }
  711.         }
  712.         if ($limit > 0
  713.             && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i'$query)
  714.         {
  715.             $query rtrim($query);
  716.             if (substr($query-1== ';'{
  717.                 $query substr($query0-1);
  718.             }
  719.  
  720.             // LIMIT doesn't always come last in the query
  721.             // @see http://dev.mysql.com/doc/refman/5.0/en/select.html
  722.             $after '';
  723.             if (preg_match('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims'$query$matches)) {
  724.                 $after $matches[0];
  725.                 $query preg_replace('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims'''$query);
  726.             elseif (preg_match('/(\s+FOR\s+UPDATE\s*)$/i'$query$matches)) {
  727.                $after $matches[0];
  728.                $query preg_replace('/(\s+FOR\s+UPDATE\s*)$/im'''$query);
  729.             elseif (preg_match('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im'$query$matches)) {
  730.                $after $matches[0];
  731.                $query preg_replace('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im'''$query);
  732.             }
  733.  
  734.             if ($is_manip{
  735.                 return $query . " LIMIT $limit" . $after;
  736.             else {
  737.                 return $query . " LIMIT $offset$limit" . $after;
  738.             }
  739.         }
  740.         return $query;
  741.     }
  742.  
  743.     // }}}
  744.     // {{{ getServerVersion()
  745.  
  746.     /**
  747.      * return version information about the server
  748.      *
  749.      * @param bool   $native  determines if the raw version string should be returned
  750.      * @return mixed array/string with version information or MDB2 error object
  751.      * @access public
  752.      */
  753.     function getServerVersion($native = false)
  754.     {
  755.         $connection $this->getConnection();
  756.         if (PEAR::isError($connection)) {
  757.             return $connection;
  758.         }
  759.         if ($this->connected_server_info{
  760.             $server_info $this->connected_server_info;
  761.         else {
  762.             $server_info @mysqli_get_server_info($connection);
  763.         }
  764.         if (!$server_info{
  765.             return $this->raiseError(nullnullnull,
  766.                 'Could not get server information'__FUNCTION__);
  767.         }
  768.         // cache server_info
  769.         $this->connected_server_info $server_info;
  770.         if (!$native{
  771.             $tmp explode('.'$server_info3);
  772.             if (isset($tmp[2]&& strpos($tmp[2]'-')) {
  773.                 $tmp2 explode('-'@$tmp[2]2);
  774.             else {
  775.                 $tmp2[0= isset($tmp[2]$tmp[2: null;
  776.                 $tmp2[1= null;
  777.             }
  778.             $server_info = array(
  779.                 'major' => isset($tmp[0]$tmp[0: null,
  780.                 'minor' => isset($tmp[1]$tmp[1: null,
  781.                 'patch' => $tmp2[0],
  782.                 'extra' => $tmp2[1],
  783.                 'native' => $server_info,
  784.             );
  785.         }
  786.         return $server_info;
  787.     }
  788.  
  789.     // }}}
  790.     // {{{ _getServerCapabilities()
  791.  
  792.     /**
  793.      * Fetch some information about the server capabilities
  794.      * (transactions, subselects, prepared statements, etc).
  795.      *
  796.      * @access private
  797.      */
  798.     function _getServerCapabilities()
  799.     {
  800.         if (!$this->server_capabilities_checked{
  801.             $this->server_capabilities_checked = true;
  802.  
  803.             //set defaults
  804.             $this->supported['sub_selects''emulated';
  805.             $this->supported['prepared_statements''emulated';
  806.             $this->start_transaction = false;
  807.             $this->varchar_max_length = 255;
  808.  
  809.             $server_info $this->getServerVersion();
  810.             if (is_array($server_info)) {
  811.                 if (!version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch']'4.1.0''<')) {
  812.                     $this->supported['sub_selects'= true;
  813.                     $this->supported['prepared_statements'= true;
  814.                 }
  815.  
  816.                 if (!version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch']'4.0.14''<')
  817.                     || !version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch']'4.1.1''<')
  818.                 {
  819.                     $this->supported['savepoints'= true;
  820.                 }
  821.  
  822.                 if (!version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch']'4.0.11''<')) {
  823.                     $this->start_transaction = true;
  824.                 }
  825.  
  826.                 if (!version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch']'5.0.3''<')) {
  827.                     $this->varchar_max_length = 65532;
  828.                 }
  829.             }
  830.         }
  831.     }
  832.  
  833.     // }}}
  834.     // {{{ function _skipUserDefinedVariable($query, $position)
  835.  
  836.     /**
  837.      * Utility method, used by prepare() to avoid misinterpreting MySQL user
  838.      * defined variables (SELECT @x:=5) for placeholders.
  839.      * Check if the placeholder is a false positive, i.e. if it is an user defined
  840.      * variable instead. If so, skip it and advance the position, otherwise
  841.      * return the current position, which is valid
  842.      *
  843.      * @param string $query 
  844.      * @param integer $position current string cursor position
  845.      * @return integer $new_position
  846.      * @access protected
  847.      */
  848.     function _skipUserDefinedVariable($query$position)
  849.     {
  850.         $found strpos(strrev(substr($query0$position))'@');
  851.         if ($found === false{
  852.             return $position;
  853.         }
  854.         $pos strlen($querystrlen(substr($query$position)) $found - 1;
  855.         $substring substr($query$pos$position $pos + 2);
  856.         if (preg_match('/^@\w+\s*:=$/'$substring)) {
  857.             return $position + 1; //found an user defined variable: skip it
  858.         }
  859.         return $position;
  860.     }
  861.  
  862.     // }}}
  863.     // {{{ prepare()
  864.  
  865.     /**
  866.      * Prepares a query for multiple execution with execute().
  867.      * With some database backends, this is emulated.
  868.      * prepare() requires a generic query as string like
  869.      * 'INSERT INTO numbers VALUES(?,?)' or
  870.      * 'INSERT INTO numbers VALUES(:foo,:bar)'.
  871.      * The ? and :name and are placeholders which can be set using
  872.      * bindParam() and the query can be sent off using the execute() method.
  873.      * The allowed format for :name can be set with the 'bindname_format' option.
  874.      *
  875.      * @param string $query the query to prepare
  876.      * @param mixed   $types  array that contains the types of the placeholders
  877.      * @param mixed   $result_types  array that contains the types of the columns in
  878.      *                         the result set or MDB2_PREPARE_RESULT, if set to
  879.      *                         MDB2_PREPARE_MANIP the query is handled as a manipulation query
  880.      * @param mixed   $lobs   key (field) value (parameter) pair for all lob placeholders
  881.      * @return mixed resource handle for the prepared query on success, a MDB2
  882.      *         error on failure
  883.      * @access public
  884.      * @see bindParam, execute
  885.      */
  886.     function &prepare($query$types = null$result_types = null$lobs = array())
  887.     {
  888.         if ($this->options['emulate_prepared']
  889.             || $this->supported['prepared_statements'!== true
  890.         {
  891.             $obj =parent::prepare($query$types$result_types$lobs);
  892.             return $obj;
  893.         }
  894.         $is_manip ($result_types === MDB2_PREPARE_MANIP);
  895.         $offset $this->offset;
  896.         $limit $this->limit;
  897.         $this->offset $this->limit = 0;
  898.         $query $this->_modifyQuery($query$is_manip$limit$offset);
  899.         $result $this->debug($query__FUNCTION__array('is_manip' => $is_manip'when' => 'pre'));
  900.         if ($result{
  901.             if (PEAR::isError($result)) {
  902.                 return $result;
  903.             }
  904.             $query $result;
  905.         }
  906.         $placeholder_type_guess $placeholder_type = null;
  907.         $question '?';
  908.         $colon ':';
  909.         $positions = array();
  910.         $position = 0;
  911.         while ($position strlen($query)) {
  912.             $q_position strpos($query$question$position);
  913.             $c_position strpos($query$colon$position);
  914.             if ($q_position && $c_position{
  915.                 $p_position min($q_position$c_position);
  916.             elseif ($q_position{
  917.                 $p_position $q_position;
  918.             elseif ($c_position{
  919.                 $p_position $c_position;
  920.             else {
  921.                 break;
  922.             }
  923.             if (is_null($placeholder_type)) {
  924.                 $placeholder_type_guess $query[$p_position];
  925.             }
  926.             
  927.             $new_pos $this->_skipDelimitedStrings($query$position$p_position);
  928.             if (PEAR::isError($new_pos)) {
  929.                 return $new_pos;
  930.             }
  931.             if ($new_pos != $position{
  932.                 $position $new_pos;
  933.                 continue; //evaluate again starting from the new position
  934.             }
  935.             
  936.             //make sure this is not part of an user defined variable
  937.             $new_pos $this->_skipUserDefinedVariable($query$position);
  938.             if ($new_pos != $position{
  939.                 $position $new_pos;
  940.                 continue; //evaluate again starting from the new position
  941.             }
  942.  
  943.             if ($query[$position== $placeholder_type_guess{
  944.                 if (is_null($placeholder_type)) {
  945.                     $placeholder_type $query[$p_position];
  946.                     $question $colon $placeholder_type;
  947.                 }
  948.                 if ($placeholder_type == ':'{
  949.                     $regexp '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
  950.                     $parameter preg_replace($regexp'\\1'$query);
  951.                     if ($parameter === ''{
  952.                         $err =$this->raiseError(MDB2_ERROR_SYNTAXnullnull,
  953.                             'named parameter name must match "bindname_format" option'__FUNCTION__);
  954.                         return $err;
  955.                     }
  956.                     $positions[$p_position$parameter;
  957.                     $query substr_replace($query'?'$positionstrlen($parameter)+1);
  958.                 else {
  959.                     $positions[$p_positioncount($positions);
  960.                 }
  961.                 $position $p_position + 1;
  962.             else {
  963.                 $position $p_position;
  964.             }
  965.         }
  966.         $connection $this->getConnection();
  967.         if (PEAR::isError($connection)) {
  968.             return $connection;
  969.         }
  970.  
  971.         if (!$is_manip{
  972.             static $prep_statement_counter = 1;
  973.             $statement_name = sprintf($this->options['statement_format']$this->phptypesha1(microtime(+ mt_rand())) $prep_statement_counter++;
  974.             $query = "PREPARE $statement_name FROM ".$this->quote($query'text');
  975.  
  976.             $statement =$this->_doQuery($querytrue$connection);
  977.             if (PEAR::isError($statement)) {
  978.                 return $statement;
  979.             }
  980.             $statement $statement_name;
  981.         else {
  982.             $statement @mysqli_prepare($connection$query);
  983.             if (!$statement{
  984.                 $err =$this->raiseError(nullnullnull,
  985.                     'Unable to create prepared statement handle'__FUNCTION__);
  986.                 return $err;
  987.             }
  988.         }
  989.  
  990.         $class_name 'MDB2_Statement_'.$this->phptype;
  991.         $obj = new $class_name($this$statement$positions$query$types$result_types$is_manip$limit$offset);
  992.         $this->debug($query__FUNCTION__array('is_manip' => $is_manip'when' => 'post''result' => $obj));
  993.         return $obj;
  994.     }
  995.  
  996.     // }}}
  997.     // {{{ replace()
  998.  
  999.     /**
  1000.      * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
  1001.      * query, except that if there is already a row in the table with the same
  1002.      * key field values, the REPLACE query just updates its values instead of
  1003.      * inserting a new row.
  1004.      *
  1005.      * The REPLACE type of query does not make part of the SQL standards. Since
  1006.      * practically only MySQL implements it natively, this type of query is
  1007.      * emulated through this method for other DBMS using standard types of
  1008.      * queries inside a transaction to assure the atomicity of the operation.
  1009.      *
  1010.      * @access public
  1011.      *
  1012.      * @param string $table name of the table on which the REPLACE query will
  1013.      *   be executed.
  1014.      * @param array $fields associative array that describes the fields and the
  1015.      *   values that will be inserted or updated in the specified table. The
  1016.      *   indexes of the array are the names of all the fields of the table. The
  1017.      *   values of the array are also associative arrays that describe the
  1018.      *   values and other properties of the table fields.
  1019.      *
  1020.      *   Here follows a list of field properties that need to be specified:
  1021.      *
  1022.      *     value:
  1023.      *           Value to be assigned to the specified field. This value may be
  1024.      *           of specified in database independent type format as this
  1025.      *           function can perform the necessary datatype conversions.
  1026.      *
  1027.      *     Default:
  1028.      *           this property is required unless the Null property
  1029.      *           is set to 1.
  1030.      *
  1031.      *     type
  1032.      *           Name of the type of the field. Currently, all types Metabase
  1033.      *           are supported except for clob and blob.
  1034.      *
  1035.      *     Default: no type conversion
  1036.      *
  1037.      *     null
  1038.      *           Boolean property that indicates that the value for this field
  1039.      *           should be set to null.
  1040.      *
  1041.      *           The default value for fields missing in INSERT queries may be
  1042.      *           specified the definition of a table. Often, the default value
  1043.      *           is already null, but since the REPLACE may be emulated using
  1044.      *           an UPDATE query, make sure that all fields of the table are
  1045.      *           listed in this function argument array.
  1046.      *
  1047.      *     Default: 0
  1048.      *
  1049.      *     key
  1050.      *           Boolean property that indicates that this field should be
  1051.      *           handled as a primary key or at least as part of the compound
  1052.      *           unique index of the table that will determine the row that will
  1053.      *           updated if it exists or inserted a new row otherwise.
  1054.      *
  1055.      *           This function will fail if no key field is specified or if the
  1056.      *           value of a key field is set to null because fields that are
  1057.      *           part of unique index they may not be null.
  1058.      *
  1059.      *     Default: 0
  1060.      *
  1061.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1062.      */
  1063.     function replace($table$fields)
  1064.     {
  1065.         $count count($fields);
  1066.         $query $values '';
  1067.         $keys $colnum = 0;
  1068.         for (reset($fields)$colnum $countnext($fields)$colnum++{
  1069.             $name key($fields);
  1070.             if ($colnum > 0{
  1071.                 $query .= ',';
  1072.                 $values.= ',';
  1073.             }
  1074.             $query.= $name;
  1075.             if (isset($fields[$name]['null']&& $fields[$name]['null']{
  1076.                 $value 'NULL';
  1077.             else {
  1078.                 $type = isset($fields[$name]['type']$fields[$name]['type': null;
  1079.                 $value $this->quote($fields[$name]['value']$type);
  1080.                 if (PEAR::isError($value)) {
  1081.                     return $value;
  1082.                 }
  1083.             }
  1084.             $values.= $value;
  1085.             if (isset($fields[$name]['key']&& $fields[$name]['key']{
  1086.                 if ($value === 'NULL'{
  1087.                     return $this->raiseError(MDB2_ERROR_CANNOT_REPLACEnullnull,
  1088.                         'key value '.$name.' may not be NULL'__FUNCTION__);
  1089.                 }
  1090.                 $keys++;
  1091.             }
  1092.         }
  1093.         if ($keys == 0{
  1094.             return $this->raiseError(MDB2_ERROR_CANNOT_REPLACEnullnull,
  1095.                 'not specified which fields are keys'__FUNCTION__);
  1096.         }
  1097.  
  1098.         $connection $this->getConnection();
  1099.         if (PEAR::isError($connection)) {
  1100.             return $connection;
  1101.         }
  1102.  
  1103.         $query = "REPLACE INTO $table ($query) VALUES ($values)";
  1104.         $result =$this->_doQuery($querytrue$connection);
  1105.         if (PEAR::isError($result)) {
  1106.             return $result;
  1107.         }
  1108.         return $this->_affectedRows($connection$result);
  1109.     }
  1110.  
  1111.     // }}}
  1112.     // {{{ nextID()
  1113.  
  1114.     /**
  1115.      * Returns the next free id of a sequence
  1116.      *
  1117.      * @param string $seq_name name of the sequence
  1118.      * @param boolean $ondemand when true the sequence is
  1119.      *                           automatic created, if it
  1120.      *                           not exists
  1121.      *
  1122.      * @return mixed MDB2 Error Object or id
  1123.      * @access public
  1124.      */
  1125.     function nextID($seq_name$ondemand = true)
  1126.     {
  1127.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  1128.         $seqcol_name $this->quoteIdentifier($this->options['seqcol_name']true);
  1129.         $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
  1130.         $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  1131.         $result =$this->_doQuery($querytrue);
  1132.         $this->popExpect();
  1133.         if (PEAR::isError($result)) {
  1134.             if ($ondemand && $result->getCode(== MDB2_ERROR_NOSUCHTABLE{
  1135.                 $this->loadModule('Manager'nulltrue);
  1136.                 $result $this->manager->createSequence($seq_name);
  1137.                 if (PEAR::isError($result)) {
  1138.                     return $this->raiseError($resultnullnull,
  1139.                         'on demand sequence '.$seq_name.' could not be created'__FUNCTION__);
  1140.                 else {
  1141.                     return $this->nextID($seq_namefalse);
  1142.                 }
  1143.             }
  1144.             return $result;
  1145.         }
  1146.         $value $this->lastInsertID();
  1147.         if (is_numeric($value)) {
  1148.             $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
  1149.             $result =$this->_doQuery($querytrue);
  1150.             if (PEAR::isError($result)) {
  1151.                 $this->warnings['nextID: could not delete previous sequence table values from '.$seq_name;
  1152.             }
  1153.         }
  1154.         return $value;
  1155.     }
  1156.  
  1157.     // }}}
  1158.     // {{{ lastInsertID()
  1159.  
  1160.     /**
  1161.      * Returns the autoincrement ID if supported or $id or fetches the current
  1162.      * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
  1163.      *
  1164.      * @param string $table name of the table into which a new row was inserted
  1165.      * @param string $field name of the field into which a new row was inserted
  1166.      * @return mixed MDB2 Error Object or id
  1167.      * @access public
  1168.      */
  1169.     function lastInsertID($table = null$field = null)
  1170.     {
  1171.         // not using mysql_insert_id() due to http://pear.php.net/bugs/bug.php?id=8051
  1172.         return $this->queryOne('SELECT LAST_INSERT_ID()''integer');
  1173.     }
  1174.  
  1175.     // }}}
  1176.     // {{{ currID()
  1177.  
  1178.     /**
  1179.      * Returns the current id of a sequence
  1180.      *
  1181.      * @param string $seq_name name of the sequence
  1182.      * @return mixed MDB2 Error Object or id
  1183.      * @access public
  1184.      */
  1185.     function currID($seq_name)
  1186.     {
  1187.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  1188.         $seqcol_name $this->quoteIdentifier($this->options['seqcol_name']true);
  1189.         $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
  1190.         return $this->queryOne($query'integer');
  1191.     }
  1192. }
  1193.  
  1194. /**
  1195.  * MDB2 MySQLi result driver
  1196.  *
  1197.  * @package MDB2
  1198.  * @category Database
  1199.  * @author  Lukas Smith <smith@pooteeweet.org>
  1200.  */
  1201. class MDB2_Result_mysqli extends MDB2_Result_Common
  1202. {
  1203.     // }}}
  1204.     // {{{ fetchRow()
  1205.  
  1206.     /**
  1207.      * Fetch a row and insert the data into an existing array.
  1208.      *
  1209.      * @param int       $fetchmode  how the array data should be indexed
  1210.      * @param int    $rownum    number of the row where the data can be found
  1211.      * @return int data array on success, a MDB2 error on failure
  1212.      * @access public
  1213.      */
  1214.     function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT$rownum = null)
  1215.     {
  1216.         if (!is_null($rownum)) {
  1217.             $seek $this->seek($rownum);
  1218.             if (PEAR::isError($seek)) {
  1219.                 return $seek;
  1220.             }
  1221.         }
  1222.         if ($fetchmode == MDB2_FETCHMODE_DEFAULT{
  1223.             $fetchmode $this->db->fetchmode;
  1224.         }
  1225.         if ($fetchmode MDB2_FETCHMODE_ASSOC{
  1226.             $row @mysqli_fetch_assoc($this->result);
  1227.             if (is_array($row)
  1228.                 && $this->db->options['portability'MDB2_PORTABILITY_FIX_CASE
  1229.             {
  1230.                 $row array_change_key_case($row$this->db->options['field_case']);
  1231.             }
  1232.         else {
  1233.            $row @mysqli_fetch_row($this->result);
  1234.         }
  1235.  
  1236.         if (!$row{
  1237.             if ($this->result === false{
  1238.                 $err =$this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1239.                     'resultset has already been freed'__FUNCTION__);
  1240.                 return $err;
  1241.             }
  1242.             $null = null;
  1243.             return $null;
  1244.         }
  1245.         $mode $this->db->options['portability'MDB2_PORTABILITY_EMPTY_TO_NULL;
  1246.         $rtrim = false;
  1247.         if ($this->db->options['portability'MDB2_PORTABILITY_RTRIM{
  1248.             if (empty($this->types)) {
  1249.                 $mode += MDB2_PORTABILITY_RTRIM;
  1250.             else {
  1251.                 $rtrim = true;
  1252.             }
  1253.         }
  1254.         if ($mode{
  1255.             $this->db->_fixResultArrayValues($row$mode);
  1256.         }
  1257.         if (!empty($this->types)) {
  1258.             $row $this->db->datatype->convertResultRow($this->types$row$rtrim);
  1259.         }
  1260.         if (!empty($this->values)) {
  1261.             $this->_assignBindColumns($row);
  1262.         }
  1263.         if ($fetchmode === MDB2_FETCHMODE_OBJECT{
  1264.             $object_class $this->db->options['fetch_class'];
  1265.             if ($object_class == 'stdClass'{
  1266.                 $row = (object) $row;
  1267.             else {
  1268.                 $row &new $object_class($row);
  1269.             }
  1270.         }
  1271.         ++$this->rownum;
  1272.         return $row;
  1273.     }
  1274.  
  1275.     // }}}
  1276.     // {{{ _getColumnNames()
  1277.  
  1278.     /**
  1279.      * Retrieve the names of columns returned by the DBMS in a query result.
  1280.      *
  1281.      * @return  mixed   Array variable that holds the names of columns as keys
  1282.      *                   or an MDB2 error on failure.
  1283.      *                   Some DBMS may not return any columns when the result set
  1284.      *                   does not contain any rows.
  1285.      * @access private
  1286.      */
  1287.     function _getColumnNames()
  1288.     {
  1289.         $columns = array();
  1290.         $numcols $this->numCols();
  1291.         if (PEAR::isError($numcols)) {
  1292.             return $numcols;
  1293.         }
  1294.         for ($column = 0; $column $numcols$column++{
  1295.             $column_info @mysqli_fetch_field_direct($this->result$column);
  1296.             $columns[$column_info->name$column;
  1297.         }
  1298.         if ($this->db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  1299.             $columns array_change_key_case($columns$this->db->options['field_case']);
  1300.         }
  1301.         return $columns;
  1302.     }
  1303.  
  1304.     // }}}
  1305.     // {{{ numCols()
  1306.  
  1307.     /**
  1308.      * Count the number of columns returned by the DBMS in a query result.
  1309.      *
  1310.      * @return mixed integer value with the number of columns, a MDB2 error
  1311.      *                        on failure
  1312.      * @access public
  1313.      */
  1314.     function numCols()
  1315.     {
  1316.         $cols @mysqli_num_fields($this->result);
  1317.         if (is_null($cols)) {
  1318.             if ($this->result === false{
  1319.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1320.                     'resultset has already been freed'__FUNCTION__);
  1321.             elseif (is_null($this->result)) {
  1322.                 return count($this->types);
  1323.             }
  1324.             return $this->db->raiseError(nullnullnull,
  1325.                 'Could not get column count'__FUNCTION__);
  1326.         }
  1327.         return $cols;
  1328.     }
  1329.  
  1330.     // }}}
  1331.     // {{{ nextResult()
  1332.  
  1333.     /**
  1334.      * Move the internal result pointer to the next available result
  1335.      *
  1336.      * @return true on success, false if there is no more result set or an error object on failure
  1337.      * @access public
  1338.      */
  1339.     function nextResult()
  1340.     {
  1341.         $connection $this->db->getConnection();
  1342.         if (PEAR::isError($connection)) {
  1343.             return $connection;
  1344.         }
  1345.  
  1346.         if (!@mysqli_more_results($connection)) {
  1347.             return false;
  1348.         }
  1349.         if (!@mysqli_next_result($connection)) {
  1350.             return false;
  1351.         }
  1352.         if (!($this->result @mysqli_use_result($connection))) {
  1353.             return false;
  1354.         }
  1355.         return MDB2_OK;
  1356.     }
  1357.  
  1358.     // }}}
  1359.     // {{{ free()
  1360.  
  1361.     /**
  1362.      * Free the internal resources associated with result.
  1363.      *
  1364.      * @return boolean true on success, false if result is invalid
  1365.      * @access public
  1366.      */
  1367.     function free()
  1368.     {
  1369.         if (is_object($this->result&& $this->db->connection{
  1370.             $free @mysqli_free_result($this->result);
  1371.             if ($free === false{
  1372.                 return $this->db->raiseError(nullnullnull,
  1373.                     'Could not free result'__FUNCTION__);
  1374.             }
  1375.         }
  1376.         $this->result = false;
  1377.         return MDB2_OK;
  1378.     }
  1379. }
  1380.  
  1381. /**
  1382.  * MDB2 MySQLi buffered result driver
  1383.  *
  1384.  * @package MDB2
  1385.  * @category Database
  1386.  * @author  Lukas Smith <smith@pooteeweet.org>
  1387.  */
  1388. {
  1389.     // }}}
  1390.     // {{{ seek()
  1391.  
  1392.     /**
  1393.      * Seek to a specific row in a result set
  1394.      *
  1395.      * @param int    $rownum    number of the row where the data can be found
  1396.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1397.      * @access public
  1398.      */
  1399.     function seek($rownum = 0)
  1400.     {
  1401.         if ($this->rownum != ($rownum - 1&& !@mysqli_data_seek($this->result$rownum)) {
  1402.             if ($this->result === false{
  1403.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1404.                     'resultset has already been freed'__FUNCTION__);
  1405.             elseif (is_null($this->result)) {
  1406.                 return MDB2_OK;
  1407.             }
  1408.             return $this->db->raiseError(MDB2_ERROR_INVALIDnullnull,
  1409.                 'tried to seek to an invalid row number ('.$rownum.')'__FUNCTION__);
  1410.         }
  1411.         $this->rownum $rownum - 1;
  1412.         return MDB2_OK;
  1413.     }
  1414.  
  1415.     // }}}
  1416.     // {{{ valid()
  1417.  
  1418.     /**
  1419.      * Check if the end of the result set has been reached
  1420.      *
  1421.      * @return mixed true or false on sucess, a MDB2 error on failure
  1422.      * @access public
  1423.      */
  1424.     function valid()
  1425.     {
  1426.         $numrows $this->numRows();
  1427.         if (PEAR::isError($numrows)) {
  1428.             return $numrows;
  1429.         }
  1430.         return $this->rownum ($numrows - 1);
  1431.     }
  1432.  
  1433.     // }}}
  1434.     // {{{ numRows()
  1435.  
  1436.     /**
  1437.      * Returns the number of rows in a result object
  1438.      *
  1439.      * @return mixed MDB2 Error Object or the number of rows
  1440.      * @access public
  1441.      */
  1442.     function numRows()
  1443.     {
  1444.         $rows @mysqli_num_rows($this->result);
  1445.         if (is_null($rows)) {
  1446.             if ($this->result === false{
  1447.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1448.                     'resultset has already been freed'__FUNCTION__);
  1449.             elseif (is_null($this->result)) {
  1450.                 return 0;
  1451.             }
  1452.             return $this->db->raiseError(nullnullnull,
  1453.                 'Could not get row count'__FUNCTION__);
  1454.         }
  1455.         return $rows;
  1456.     }
  1457.  
  1458.     // }}}
  1459.     // {{{ nextResult()
  1460.  
  1461.     /**
  1462.      * Move the internal result pointer to the next available result
  1463.      *
  1464.      * @param valid result resource
  1465.      * @return true on success, false if there is no more result set or an error object on failure
  1466.      * @access public
  1467.      */
  1468.     function nextResult()
  1469.     {
  1470.         $connection $this->db->getConnection();
  1471.         if (PEAR::isError($connection)) {
  1472.             return $connection;
  1473.         }
  1474.  
  1475.         if (!@mysqli_more_results($connection)) {
  1476.             return false;
  1477.         }
  1478.         if (!@mysqli_next_result($connection)) {
  1479.             return false;
  1480.         }
  1481.         if (!($this->result @mysqli_store_result($connection))) {
  1482.             return false;
  1483.         }
  1484.         return MDB2_OK;
  1485.     }
  1486. }
  1487.  
  1488. /**
  1489.  * MDB2 MySQLi statement driver
  1490.  *
  1491.  * @package MDB2
  1492.  * @category Database
  1493.  * @author  Lukas Smith <smith@pooteeweet.org>
  1494.  */
  1495. class MDB2_Statement_mysqli extends MDB2_Statement_Common
  1496. {
  1497.     // {{{ _execute()
  1498.  
  1499.     /**
  1500.      * Execute a prepared query statement helper method.
  1501.      *
  1502.      * @param mixed $result_class string which specifies which result class to use
  1503.      * @param mixed $result_wrap_class string which specifies which class to wrap results in
  1504.      * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
  1505.      * @access private
  1506.      */
  1507.     function &_execute($result_class = true$result_wrap_class = false)
  1508.     {
  1509.         if (is_null($this->statement)) {
  1510.             $result =parent::_execute($result_class$result_wrap_class);
  1511.             return $result;
  1512.         }
  1513.         $this->db->last_query = $this->query;
  1514.         $this->db->debug($this->query'execute'array('is_manip' => $this->is_manip'when' => 'pre''parameters' => $this->values));
  1515.         if ($this->db->getOption('disable_query')) {
  1516.             $result $this->is_manip ? 0 : null;
  1517.             return $result;
  1518.         }
  1519.  
  1520.         $connection $this->db->getConnection();
  1521.         if (PEAR::isError($connection)) {
  1522.             return $connection;
  1523.         }
  1524.  
  1525.         if (!is_object($this->statement)) {
  1526.             $query 'EXECUTE '.$this->statement;
  1527.         }
  1528.         if (!empty($this->positions)) {
  1529.             $parameters = array(0 => $this->statement1 => '');
  1530.             $lobs = array();
  1531.             $i = 0;
  1532.             foreach ($this->positions as $parameter{
  1533.                 if (!array_key_exists($parameter$this->values)) {
  1534.                     return $this->db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  1535.                         'Unable to bind to missing placeholder: '.$parameter__FUNCTION__);
  1536.                 }
  1537.                 $value $this->values[$parameter];
  1538.                 $type array_key_exists($parameter$this->types$this->types[$parameter: null;
  1539.                 if (!is_object($this->statement)) {
  1540.                     if (is_resource($value|| $type == 'clob' || $type == 'blob' && $this->db->options['lob_allow_url_include']{
  1541.                         if (!is_resource($value&& preg_match('/^(\w+:\/\/)(.*)$/'$value$match)) {
  1542.                             if ($match[1== 'file://'{
  1543.                                 $value $match[2];
  1544.                             }
  1545.                             $value @fopen($value'r');
  1546.                             $close = true;
  1547.                         }
  1548.                         if (is_resource($value)) {
  1549.                             $data '';
  1550.                             while (!@feof($value)) {
  1551.                                 $data.= @fread($value$this->db->options['lob_buffer_length']);
  1552.                             }
  1553.                             if ($close{
  1554.                                 @fclose($value);
  1555.                             }
  1556.                             $value $data;
  1557.                         }
  1558.                     }
  1559.                     $quoted $this->db->quote($value$type);
  1560.                     if (PEAR::isError($quoted)) {
  1561.                         return $quoted;
  1562.                     }
  1563.                     $param_query 'SET @'.$parameter.' = '.$quoted;
  1564.                     $result $this->db->_doQuery($param_querytrue$connection);
  1565.                     if (PEAR::isError($result)) {
  1566.                         return $result;
  1567.                     }
  1568.                 else {
  1569.                     if (is_resource($value|| $type == 'clob' || $type == 'blob'{
  1570.                         $parameters[= null;
  1571.                         $parameters[1].= 'b';
  1572.                         $lobs[$i$parameter;
  1573.                     else {
  1574.                         $quoted $this->db->quote($value$typefalse);
  1575.                         if (PEAR::isError($quoted)) {
  1576.                             return $quoted;
  1577.                         }
  1578.                         $parameters[$quoted;
  1579.                         $parameters[1].= $this->db->datatype->mapPrepareDatatype($type);
  1580.                     }
  1581.                     ++$i;
  1582.                 }
  1583.             }
  1584.  
  1585.             if (!is_object($this->statement)) {
  1586.                 $query.= ' USING @'.implode(', @'array_values($this->positions));
  1587.             else {
  1588.                 $result @call_user_func_array('mysqli_stmt_bind_param'$parameters);
  1589.                 if ($result === false{
  1590.                     $err =$this->db->raiseError(nullnullnull,
  1591.                         'Unable to bind parameters'__FUNCTION__);
  1592.                     return $err;
  1593.                 }
  1594.  
  1595.                 foreach ($lobs as $i => $parameter{
  1596.                     $value $this->values[$parameter];
  1597.                     $close = false;
  1598.                     if (!is_resource($value)) {
  1599.                         $close = true;
  1600.                         if (preg_match('/^(\w+:\/\/)(.*)$/'$value$match)) {
  1601.                             if ($match[1== 'file://'{
  1602.                                 $value $match[2];
  1603.                             }
  1604.                             $value @fopen($value'r');
  1605.                         else {
  1606.                             $fp @tmpfile();
  1607.                             @fwrite($fp$value);
  1608.                             @rewind($fp);
  1609.                             $value $fp;
  1610.                         }
  1611.                     }
  1612.                     while (!@feof($value)) {
  1613.                         $data @fread($value$this->db->options['lob_buffer_length']);
  1614.                         @mysqli_stmt_send_long_data($this->statement$i$data);
  1615.                     }
  1616.                     if ($close{
  1617.                         @fclose($value);
  1618.                     }
  1619.                 }
  1620.             }
  1621.         }
  1622.  
  1623.         if (!is_object($this->statement)) {
  1624.             $result $this->db->_doQuery($query$this->is_manip$connection);
  1625.             if (PEAR::isError($result)) {
  1626.                 return $result;
  1627.             }
  1628.  
  1629.             if ($this->is_manip{
  1630.                 $affected_rows $this->db->_affectedRows($connection$result);
  1631.                 return $affected_rows;
  1632.             }
  1633.  
  1634.             $result =$this->db->_wrapResult($result$this->result_types,
  1635.                 $result_class$result_wrap_class$this->limit$this->offset);
  1636.         else {
  1637.             if (!@mysqli_stmt_execute($this->statement)) {
  1638.                 $err =$this->db->raiseError(nullnullnull,
  1639.                     'Unable to execute statement'__FUNCTION__);
  1640.                 return $err;
  1641.             }
  1642.  
  1643.             if ($this->is_manip{
  1644.                 $affected_rows @mysqli_stmt_affected_rows($this->statement);
  1645.                 return $affected_rows;
  1646.             }
  1647.  
  1648.             if ($this->db->options['result_buffering']{
  1649.                 @mysqli_stmt_store_result($this->statement);
  1650.             }
  1651.  
  1652.             $result =$this->db->_wrapResult($this->statement$this->result_types,
  1653.                 $result_class$result_wrap_class$this->limit$this->offset);
  1654.         }
  1655.  
  1656.         $this->db->debug($this->query'execute'array('is_manip' => $this->is_manip'when' => 'post''result' => $result));
  1657.         return $result;
  1658.     }
  1659.  
  1660.     // }}}
  1661.     // {{{ free()
  1662.  
  1663.     /**
  1664.      * Release resources allocated for the specified prepared query.
  1665.      *
  1666.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1667.      * @access public
  1668.      */
  1669.     function free()
  1670.     {
  1671.         if (is_null($this->positions)) {
  1672.             return $this->db->raiseError(MDB2_ERRORnullnull,
  1673.                 'Prepared statement has already been freed'__FUNCTION__);
  1674.         }
  1675.         $result = MDB2_OK;
  1676.  
  1677.         if (is_object($this->statement)) {
  1678.             if (!@mysqli_stmt_close($this->statement)) {
  1679.                 $result $this->db->raiseError(nullnullnull,
  1680.                     'Could not free statement'__FUNCTION__);
  1681.             }
  1682.         elseif (!is_null($this->statement)) {
  1683.             $connection $this->db->getConnection();
  1684.             if (PEAR::isError($connection)) {
  1685.                 return $connection;
  1686.             }
  1687.  
  1688.             $query 'DEALLOCATE PREPARE '.$this->statement;
  1689.             $result $this->db->_doQuery($querytrue$connection);
  1690.         }
  1691.  
  1692.         parent::free();
  1693.         return $result;
  1694.    }
  1695. }
  1696. ?>

Documentation generated on Mon, 11 Mar 2019 15:12:05 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.