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

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