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.57 2005/12/11 18:10:51 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 'mysqli';
  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'= false;
  85.         $this->supported['auto_increment'= true;
  86.         $this->supported['primary_key'= true;
  87.  
  88.         $this->options['default_table_type'= null;
  89.     }
  90.  
  91.     // }}}
  92.     // {{{ errorInfo()
  93.  
  94.     /**
  95.      * This method is used to collect information about an error
  96.      *
  97.      * @param integer $error 
  98.      * @return array 
  99.      * @access public
  100.      */
  101.     function errorInfo($error = null)
  102.     {
  103.         if ($this->connection{
  104.             $native_code @mysqli_errno($this->connection);
  105.             $native_msg  @mysqli_error($this->connection);
  106.         else {
  107.             $native_code @mysqli_errno();
  108.             $native_msg  @mysqli_error();
  109.         }
  110.         if (is_null($error)) {
  111.             static $ecode_map;
  112.             if (empty($ecode_map)) {
  113.                 $ecode_map = array(
  114.                     1004 => MDB2_ERROR_CANNOT_CREATE,
  115.                     1005 => MDB2_ERROR_CANNOT_CREATE,
  116.                     1006 => MDB2_ERROR_CANNOT_CREATE,
  117.                     1007 => MDB2_ERROR_ALREADY_EXISTS,
  118.                     1008 => MDB2_ERROR_CANNOT_DROP,
  119.                     1022 => MDB2_ERROR_ALREADY_EXISTS,
  120.                     1044 => MDB2_ERROR_ACCESS_VIOLATION,
  121.                     1046 => MDB2_ERROR_NODBSELECTED,
  122.                     1048 => MDB2_ERROR_CONSTRAINT,
  123.                     1049 => MDB2_ERROR_NOSUCHDB,
  124.                     1050 => MDB2_ERROR_ALREADY_EXISTS,
  125.                     1051 => MDB2_ERROR_NOSUCHTABLE,
  126.                     1054 => MDB2_ERROR_NOSUCHFIELD,
  127.                     1061 => MDB2_ERROR_ALREADY_EXISTS,
  128.                     1062 => MDB2_ERROR_ALREADY_EXISTS,
  129.                     1064 => MDB2_ERROR_SYNTAX,
  130.                     1091 => MDB2_ERROR_NOT_FOUND,
  131.                     1100 => MDB2_ERROR_NOT_LOCKED,
  132.                     1136 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
  133.                     1142 => MDB2_ERROR_ACCESS_VIOLATION,
  134.                     1146 => MDB2_ERROR_NOSUCHTABLE,
  135.                     1216 => MDB2_ERROR_CONSTRAINT,
  136.                     1217 => MDB2_ERROR_CONSTRAINT,
  137.                 );
  138.             }
  139.             if ($this->options['portability'MDB2_PORTABILITY_ERRORS{
  140.                 $ecode_map[1022= MDB2_ERROR_CONSTRAINT;
  141.                 $ecode_map[1048= MDB2_ERROR_CONSTRAINT_NOT_NULL;
  142.                 $ecode_map[1062= MDB2_ERROR_CONSTRAINT;
  143.             else {
  144.                 // Doing this in case mode changes during runtime.
  145.                 $ecode_map[1022= MDB2_ERROR_ALREADY_EXISTS;
  146.                 $ecode_map[1048= MDB2_ERROR_CONSTRAINT;
  147.                 $ecode_map[1062= MDB2_ERROR_ALREADY_EXISTS;
  148.             }
  149.             if (isset($ecode_map[$native_code])) {
  150.                 $error $ecode_map[$native_code];
  151.             }
  152.         }
  153.         return array($error$native_code$native_msg);
  154.     }
  155.  
  156.     // }}}
  157.     // {{{ escape()
  158.  
  159.     /**
  160.      * Quotes a string so it can be safely used in a query. It will quote
  161.      * the text so it can safely be used within a query.
  162.      *
  163.      * @param string $text the input string to quote
  164.      * @return string quoted string
  165.      * @access public
  166.      */
  167.     function escape($text)
  168.     {
  169.         $connection $this->getConnection();
  170.         if (PEAR::isError($connection)) {
  171.             return $connection;
  172.         }
  173.         return @mysqli_escape_string($connection$text);
  174.     }
  175.  
  176.     // }}}
  177.     // {{{ quoteIdentifier()
  178.  
  179.     /**
  180.      * Quote a string so it can be safely used as a table or column name
  181.      *
  182.      * Quoting style depends on which database driver is being used.
  183.      *
  184.      * MySQL can't handle the backtick character (<kbd>`</kbd>) in
  185.      * table or column names.
  186.      *
  187.      * @param string $str  identifier name to be quoted
  188.      * @param bool   $check_option  check the 'quote_identifier' option
  189.      *
  190.      * @return string  quoted identifier string
  191.      *
  192.      * @access public
  193.      */
  194.     function quoteIdentifier($str$check_option)
  195.     {
  196.         if ($check_option && !$this->options['quote_identifier']{
  197.             return $str;
  198.         }
  199.         return '`' $str '`';
  200.     }
  201.  
  202.     // }}}
  203.     // {{{ beginTransaction()
  204.  
  205.     /**
  206.      * Start a transaction.
  207.      *
  208.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  209.      * @access public
  210.      */
  211.     function beginTransaction()
  212.     {
  213.         $this->debug('starting transaction''beginTransaction');
  214.         if (!$this->supports('transactions')) {
  215.             return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  216.                 'beginTransaction: transactions are not in use');
  217.         }
  218.         if ($this->in_transaction{
  219.             return MDB2_OK;  //nothing to do
  220.         }
  221.         $result $this->_doQuery('SET AUTOCOMMIT = 0'true);
  222.         if (PEAR::isError($result)) {
  223.             return $result;
  224.         }
  225.         $this->in_transaction = true;
  226.         return MDB2_OK;
  227.     }
  228.  
  229.     // }}}
  230.     // {{{ commit()
  231.  
  232.     /**
  233.      * Commit the database changes done during a transaction that is in
  234.      * progress.
  235.      *
  236.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  237.      * @access public
  238.      */
  239.     function commit()
  240.     {
  241.         $this->debug('commit transaction''commit');
  242.         if (!$this->supports('transactions')) {
  243.             return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  244.                 'commit: transactions are not in use');
  245.         }
  246.         if (!$this->in_transaction{
  247.             return $this->raiseError(MDB2_ERRORnullnull,
  248.                 'commit: transaction changes are being auto committed');
  249.         }
  250.         $result $this->_doQuery('COMMIT'true);
  251.         if (PEAR::isError($result)) {
  252.             return $result;
  253.         }
  254.         $result $this->_doQuery('SET AUTOCOMMIT = 1'true);
  255.         if (PEAR::isError($result)) {
  256.             return $result;
  257.         }
  258.         $this->in_transaction = false;
  259.         return MDB2_OK;
  260.     }
  261.  
  262.     // }}}
  263.     // {{{ rollback()
  264.  
  265.     /**
  266.      * Cancel any database changes done during a transaction that is in
  267.      * progress.
  268.      *
  269.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  270.      * @access public
  271.      */
  272.     function rollback()
  273.     {
  274.         $this->debug('rolling back transaction''rollback');
  275.         if (!$this->supports('transactions')) {
  276.             return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  277.                 'rollback: transactions are not in use');
  278.         }
  279.         if (!$this->in_transaction{
  280.             return $this->raiseError(MDB2_ERRORnullnull,
  281.                 'rollback: transactions can not be rolled back when changes are auto committed');
  282.         }
  283.         $result $this->_doQuery('ROLLBACK'true);
  284.         if (PEAR::isError($result)) {
  285.             return $result;
  286.         }
  287.         $result $this->_doQuery('SET AUTOCOMMIT = 1'true);
  288.         if (PEAR::isError($result)) {
  289.             return $result;
  290.         }
  291.         $this->in_transaction = false;
  292.         return MDB2_OK;
  293.  
  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.         $server_info $this->getServerVersion();
  398.         if (is_array($server_info)
  399.             && ($server_info['major'> 4)
  400.                 || ($server_info['major'> 4 && $server_info['minor'> 1)
  401.             )
  402.         {
  403.             $this->supported['sub_selects'= true;
  404.         }
  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['result_buffering']
  477.             ? 'mysqli_query' 'mysqli_unbuffered_query';
  478.         $result @$function($connection$query);
  479.  
  480.         if (!$result{
  481.             return $this->raiseError();
  482.         }
  483.  
  484.         return $result;
  485.     }
  486.  
  487.     // }}}
  488.     // {{{ _affectedRows()
  489.  
  490.     /**
  491.      * returns the number of rows affected
  492.      *
  493.      * @param resource $result 
  494.      * @param resource $connection 
  495.      * @return mixed MDB2 Error Object or the number of rows affected
  496.      * @access private
  497.      */
  498.     function _affectedRows($connection$result = null)
  499.     {
  500.         if (is_null($connection)) {
  501.             $connection $this->getConnection();
  502.             if (PEAR::isError($connection)) {
  503.                 return $connection;
  504.             }
  505.         }
  506.         return mysqli_affected_rows($connection);
  507.     }
  508.  
  509.     // }}}
  510.     // {{{ _modifyQuery()
  511.  
  512.     /**
  513.      * Changes a query string for various DBMS specific reasons
  514.      *
  515.      * @param string $query  query to modify
  516.      * @return the new (modified) query
  517.      * @access protected
  518.      */
  519.     function _modifyQuery($query$is_manip$limit$offset)
  520.     {
  521.         if ($limit > 0
  522.             && !preg_match('/LIMIT\s*\d(\s*(,|OFFSET)\s*\d+)?/i'$query)
  523.         {
  524.             $query rtrim($query);
  525.             if (substr($query-1== ';'{
  526.                 $query substr($query0-1);
  527.             }
  528.             if ($is_manip{
  529.                 return $query . " LIMIT $limit";
  530.             else {
  531.                 return $query . " LIMIT $offset$limit";
  532.             }
  533.         }
  534.         return $query;
  535.     }
  536.  
  537.     // }}}
  538.     // {{{ getServerVersion()
  539.  
  540.     /**
  541.      * return version information about the server
  542.      *
  543.      * @param string     $native  determines if the raw version string should be returned
  544.      * @return mixed array with versoin information or row string
  545.      * @access public
  546.      */
  547.     function getServerVersion($native = false)
  548.     {
  549.         $connection $this->getConnection();
  550.         if (PEAR::isError($connection)) {
  551.             return $connection;
  552.         }
  553.         $server_info mysqli_get_server_info($connection);
  554.         if (!$native{
  555.             $tmp explode('.'$server_info);
  556.             $tmp2 explode('-'@$tmp[2]);
  557.             $server_info = array(
  558.                 'major' => @$tmp[0],
  559.                 'minor' => @$tmp[1],
  560.                 'patch' => @$tmp2[0],
  561.                 'extra' => @$tmp2[1],
  562.                 'native' => $server_info,
  563.             );
  564.         }
  565.         return $server_info;
  566.     }
  567.  
  568.     // }}}
  569.     // {{{ prepare()
  570.  
  571.     /**
  572.      * Prepares a query for multiple execution with execute().
  573.      * With some database backends, this is emulated.
  574.      * prepare() requires a generic query as string like
  575.      * 'INSERT INTO numbers VALUES(?,?)' or
  576.      * 'INSERT INTO numbers VALUES(:foo,:bar)'.
  577.      * The ? and :[a-zA-Z] and  are placeholders which can be set using
  578.      * bindParam() and the query can be send off using the execute() method.
  579.      *
  580.      * @param string $query the query to prepare
  581.      * @param mixed   $types  array that contains the types of the placeholders
  582.      * @param mixed   $result_types  array that contains the types of the columns in
  583.      *                         the result set, if set to MDB2_PREPARE_MANIP the
  584.                               query is handled as a manipulation query
  585.      * @return mixed resource handle for the prepared query on success, a MDB2
  586.      *         error on failure
  587.      * @access public
  588.      * @see bindParam, execute
  589.      */
  590.     function &prepare($query$types = null$result_types = null)
  591.     {
  592.         $is_manip ($result_types === MDB2_PREPARE_MANIP);
  593.         $query $this->_modifyQuery($query$is_manip$this->row_limit$this->row_offset);
  594.         $this->debug($query'prepare');
  595.         $placeholder_type_guess $placeholder_type = null;
  596.         $question '?';
  597.         $colon ':';
  598.         $position = 0;
  599.         while ($position strlen($query)) {
  600.             $q_position strpos($query$question$position);
  601.             $c_position strpos($query$colon$position);
  602.             if ($q_position && $c_position{
  603.                 $p_position min($q_position$c_position);
  604.             elseif ($q_position{
  605.                 $p_position $q_position;
  606.             elseif ($c_position{
  607.                 $p_position $c_position;
  608.             else {
  609.                 break;
  610.             }
  611.             if (is_null($placeholder_type)) {
  612.                 $placeholder_type_guess $query[$p_position];
  613.             }
  614.             if (is_int($quote strpos($query"'"$position)) && $quote $p_position{
  615.                 if (!is_int($end_quote strpos($query"'"$quote + 1))) {
  616.                     $err =$this->raiseError(MDB2_ERROR_SYNTAXnullnull,
  617.                         'prepare: query with an unterminated text string specified');
  618.                     return $err;
  619.                 }
  620.                 switch ($this->escape_quotes{
  621.                 case '':
  622.                 case "'":
  623.                     $position $end_quote + 1;
  624.                     break;
  625.                 default:
  626.                     if ($end_quote == $quote + 1{
  627.                         $position $end_quote + 1;
  628.                     else {
  629.                         if ($query[$end_quote-1== $this->escape_quotes{
  630.                             $position $end_quote;
  631.                         else {
  632.                             $position $end_quote + 1;
  633.                         }
  634.                     }
  635.                     break;
  636.                 }
  637.             elseif ($query[$position== $placeholder_type_guess{
  638.                 if ($placeholder_type_guess == '?'{
  639.                     break;
  640.                 }
  641.                 if (is_null($placeholder_type)) {
  642.                     $placeholder_type $query[$p_position];
  643.                     $question $colon $placeholder_type;
  644.                 }
  645.                 $name preg_replace('/^.{'.($position+1).'}([a-z0-9_]+).*$/si''\\1'$query);
  646.                 if ($name === ''{
  647.                     $err =$this->raiseError(MDB2_ERROR_SYNTAXnullnull,
  648.                         'prepare: named parameter with an empty name');
  649.                     return $err;
  650.                 }
  651.                 $query substr_replace($query'?'$positionstrlen($name)+1);
  652.                 $position $p_position + 1;
  653.             else {
  654.                 $position $p_position;
  655.             }
  656.         }
  657.         $connection $this->getConnection();
  658.         if (PEAR::isError($connection)) {
  659.             return $connection;
  660.         }
  661.         $statement @mysqli_prepare($connection$query);
  662.         $class_name 'MDB2_Statement_'.$this->phptype;
  663.         $obj =new $class_name($this$statement$query$types$result_types$is_manip$this->row_limit$this->row_offset);
  664.         return $obj;
  665.     }
  666.  
  667.     // }}}
  668.     // {{{ replace()
  669.  
  670.     /**
  671.      * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
  672.      * query, except that if there is already a row in the table with the same
  673.      * key field values, the REPLACE query just updates its values instead of
  674.      * inserting a new row.
  675.      *
  676.      * The REPLACE type of query does not make part of the SQL standards. Since
  677.      * practically only MySQL implements it natively, this type of query is
  678.      * emulated through this method for other DBMS using standard types of
  679.      * queries inside a transaction to assure the atomicity of the operation.
  680.      *
  681.      * @access public
  682.      *
  683.      * @param string $table name of the table on which the REPLACE query will
  684.      *   be executed.
  685.      * @param array $fields associative array that describes the fields and the
  686.      *   values that will be inserted or updated in the specified table. The
  687.      *   indexes of the array are the names of all the fields of the table. The
  688.      *   values of the array are also associative arrays that describe the
  689.      *   values and other properties of the table fields.
  690.      *
  691.      *   Here follows a list of field properties that need to be specified:
  692.      *
  693.      *     value:
  694.      *           Value to be assigned to the specified field. This value may be
  695.      *           of specified in database independent type format as this
  696.      *           function can perform the necessary datatype conversions.
  697.      *
  698.      *     Default:
  699.      *           this property is required unless the Null property
  700.      *           is set to 1.
  701.      *
  702.      *     type
  703.      *           Name of the type of the field. Currently, all types Metabase
  704.      *           are supported except for clob and blob.
  705.      *
  706.      *     Default: no type conversion
  707.      *
  708.      *     null
  709.      *           Boolean property that indicates that the value for this field
  710.      *           should be set to null.
  711.      *
  712.      *           The default value for fields missing in INSERT queries may be
  713.      *           specified the definition of a table. Often, the default value
  714.      *           is already null, but since the REPLACE may be emulated using
  715.      *           an UPDATE query, make sure that all fields of the table are
  716.      *           listed in this function argument array.
  717.      *
  718.      *     Default: 0
  719.      *
  720.      *     key
  721.      *           Boolean property that indicates that this field should be
  722.      *           handled as a primary key or at least as part of the compound
  723.      *           unique index of the table that will determine the row that will
  724.      *           updated if it exists or inserted a new row otherwise.
  725.      *
  726.      *           This function will fail if no key field is specified or if the
  727.      *           value of a key field is set to null because fields that are
  728.      *           part of unique index they may not be null.
  729.      *
  730.      *     Default: 0
  731.      *
  732.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  733.      */
  734.     function replace($table$fields)
  735.     {
  736.         $count count($fields);
  737.         $query $values '';
  738.         $keys $colnum = 0;
  739.         for (reset($fields)$colnum $countnext($fields)$colnum++{
  740.             $name key($fields);
  741.             if ($colnum > 0{
  742.                 $query .= ',';
  743.                 $values.= ',';
  744.             }
  745.             $query.= $name;
  746.             if (isset($fields[$name]['null']&& $fields[$name]['null']{
  747.                 $value 'NULL';
  748.             else {
  749.                 $value $this->quote($fields[$name]['value']$fields[$name]['type']);
  750.             }
  751.             $values.= $value;
  752.             if (isset($fields[$name]['key']&& $fields[$name]['key']{
  753.                 if ($value === 'NULL'{
  754.                     return $this->raiseError(MDB2_ERROR_CANNOT_REPLACEnullnull,
  755.                         'replace: key value '.$name.' may not be NULL');
  756.                 }
  757.                 $keys++;
  758.             }
  759.         }
  760.         if ($keys == 0{
  761.             return $this->raiseError(MDB2_ERROR_CANNOT_REPLACEnullnull,
  762.                 'replace: not specified which fields are keys');
  763.         }
  764.  
  765.         $connection $this->getConnection();
  766.         if (PEAR::isError($connection)) {
  767.             return $connection;
  768.         }
  769.  
  770.         $query = "REPLACE INTO $table ($query) VALUES ($values)";
  771.         $this->last_query $query;
  772.         $this->debug($query'query');
  773.         $result $this->_doQuery($querytrue$connection);
  774.         if (PEAR::isError($result)) {
  775.             return $result;
  776.         }
  777.         return $this->_affectedRows($connection$result);
  778.     }
  779.  
  780.     // }}}
  781.     // {{{ nextID()
  782.  
  783.     /**
  784.      * returns the next free id of a sequence
  785.      *
  786.      * @param string $seq_name name of the sequence
  787.      * @param boolean $ondemand when true the seqence is
  788.      *                           automatic created, if it
  789.      *                           not exists
  790.      *
  791.      * @return mixed MDB2 Error Object or id
  792.      * @access public
  793.      */
  794.     function nextID($seq_name$ondemand = true)
  795.     {
  796.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  797.         $seqcol_name $this->quoteIdentifier($this->options['seqcol_name']true);
  798.         $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
  799.         $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  800.         $result $this->_doQuery($querytrue);
  801.         $this->popExpect();
  802.         if (PEAR::isError($result)) {
  803.             if ($ondemand && $result->getCode(== MDB2_ERROR_NOSUCHTABLE{
  804.                 $this->loadModule('Manager');
  805.                 // Since we are creating the sequence on demand
  806.                 // we know the first id = 1 so initialize the
  807.                 // sequence at 2
  808.                 $result $this->manager->createSequence($seq_name2);
  809.                 if (PEAR::isError($result)) {
  810.                     return $this->raiseError(MDB2_ERRORnullnull,
  811.                         'nextID: on demand sequence '.$seq_name.' could not be created');
  812.                 else {
  813.                     // First ID of a newly created sequence is 1
  814.                     return 1;
  815.                 }
  816.             }
  817.             return $result;
  818.         }
  819.         $value $this->lastInsertID();
  820.         if (is_numeric($value)) {
  821.             $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
  822.             $result $this->_doQuery($querytrue);
  823.             if (PEAR::isError($result)) {
  824.                 $this->warnings['nextID: could not delete previous sequence table values from '.$seq_name;
  825.             }
  826.         }
  827.         return $value;
  828.     }
  829.  
  830.     // }}}
  831.     // {{{ lastInsertID()
  832.  
  833.     /**
  834.      * returns the autoincrement ID if supported or $id
  835.      *
  836.      * @param mixed $id value as returned by getBeforeId()
  837.      * @param string $table name of the table into which a new row was inserted
  838.      * @return mixed MDB2 Error Object or id
  839.      * @access public
  840.      */
  841.     function lastInsertID($table = null$field = null)
  842.     {
  843.         $connection $this->getConnection();
  844.         if (PEAR::isError($connection)) {
  845.             return $connection;
  846.         }
  847.         $value @mysqli_insert_id($connection);
  848.         if (!$value{
  849.             return $this->raiseError();
  850.         }
  851.         return $value;
  852.     }
  853.  
  854.     // }}}
  855.     // {{{ currID()
  856.  
  857.     /**
  858.      * returns the current id of a sequence
  859.      *
  860.      * @param string $seq_name name of the sequence
  861.      * @return mixed MDB2 Error Object or id
  862.      * @access public
  863.      */
  864.     function currID($seq_name)
  865.     {
  866.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  867.         $seqcol_name $this->quoteIdentifier($this->options['seqcol_name']true);
  868.         $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
  869.         return $this->queryOne($query'integer');
  870.     }
  871. }
  872.  
  873. class MDB2_Result_mysqli extends MDB2_Result_Common
  874. {
  875.     // }}}
  876.     // {{{ fetchRow()
  877.  
  878.     /**
  879.      * Fetch a row and insert the data into an existing array.
  880.      *
  881.      * @param int       $fetchmode  how the array data should be indexed
  882.      * @param int    $rownum    number of the row where the data can be found
  883.      * @return int data array on success, a MDB2 error on failure
  884.      * @access public
  885.      */
  886.     function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT$rownum = null)
  887.     {
  888.         if (!is_null($rownum)) {
  889.             $seek $this->seek($rownum);
  890.             if (PEAR::isError($seek)) {
  891.                 return $seek;
  892.             }
  893.         }
  894.         if ($fetchmode == MDB2_FETCHMODE_DEFAULT{
  895.             $fetchmode $this->db->fetchmode;
  896.         }
  897.         if ($fetchmode MDB2_FETCHMODE_ASSOC{
  898.             $row @mysqli_fetch_assoc($this->result);
  899.             if (is_array($row)
  900.                 && $this->db->options['portability'MDB2_PORTABILITY_FIX_CASE
  901.             {
  902.                 $row array_change_key_case($row$this->db->options['field_case']);
  903.             }
  904.         else {
  905.            $row @mysqli_fetch_row($this->result);
  906.         }
  907.  
  908.         if (!$row{
  909.             if (is_null($this->result)) {
  910.                 $err =$this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  911.                     'fetchRow: resultset has already been freed');
  912.                 return $err;
  913.             }
  914.             $null = null;
  915.             return $null;
  916.         }
  917.         if ($this->db->options['portability'MDB2_PORTABILITY_EMPTY_TO_NULL{
  918.             $this->db->_fixResultArrayValues($rowMDB2_PORTABILITY_EMPTY_TO_NULL);
  919.         }
  920.         if (!empty($this->values)) {
  921.             $this->_assignBindColumns($row);
  922.         }
  923.         if (!empty($this->types)) {
  924.             $row $this->db->datatype->convertResultRow($this->types$row);
  925.         }
  926.         if ($fetchmode === MDB2_FETCHMODE_OBJECT{
  927.             $object_class $this->db->options['fetch_class'];
  928.             if ($object_class == 'stdClass'{
  929.                 $row = (object) $row;
  930.             else {
  931.                 $row &new $object_class($row);
  932.             }
  933.         }
  934.         ++$this->rownum;
  935.         return $row;
  936.     }
  937.  
  938.     // }}}
  939.     // {{{ _getColumnNames()
  940.  
  941.     /**
  942.      * Retrieve the names of columns returned by the DBMS in a query result.
  943.      *
  944.      * @return mixed                an associative array variable
  945.      *                               that will hold the names of columns. The
  946.      *                               indexes of the array are the column names
  947.      *                               mapped to lower case and the values are the
  948.      *                               respective numbers of the columns starting
  949.      *                               from 0. Some DBMS may not return any
  950.      *                               columns when the result set does not
  951.      *                               contain any rows.
  952.      *
  953.      *                               a MDB2 error on failure
  954.      * @access private
  955.      */
  956.     function _getColumnNames()
  957.     {
  958.         $columns = array();
  959.         $numcols $this->numCols();
  960.         if (PEAR::isError($numcols)) {
  961.             return $numcols;
  962.         }
  963.         for ($column = 0; $column $numcols$column++{
  964.             $column_info @mysqli_fetch_field_direct($this->result$column);
  965.             $columns[$column_info->name$column;
  966.         }
  967.         if ($this->db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  968.             $columns array_change_key_case($columns$this->db->options['field_case']);
  969.         }
  970.         return $columns;
  971.     }
  972.  
  973.     // }}}
  974.     // {{{ numCols()
  975.  
  976.     /**
  977.      * Count the number of columns returned by the DBMS in a query result.
  978.      *
  979.      * @return mixed integer value with the number of columns, a MDB2 error
  980.      *                        on failure
  981.      * @access public
  982.      */
  983.     function numCols()
  984.     {
  985.         $cols @mysqli_num_fields($this->result);
  986.         if (is_null($cols)) {
  987.             if (is_null($this->result)) {
  988.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  989.                     'numCols: resultset has already been freed');
  990.             }
  991.             return $this->db->raiseError();
  992.         }
  993.         return $cols;
  994.     }
  995.  
  996.     // }}}
  997.     // {{{ free()
  998.  
  999.     /**
  1000.      * Free the internal resources associated with result.
  1001.      *
  1002.      * @return boolean true on success, false if result is invalid
  1003.      * @access public
  1004.      */
  1005.     function free()
  1006.     {
  1007.         @mysqli_free_result($this->result);
  1008.         $this->result = null;
  1009.         return MDB2_OK;
  1010.     }
  1011. }
  1012.  
  1013. {
  1014.     // }}}
  1015.     // {{{ seek()
  1016.  
  1017.     /**
  1018.     * seek to a specific row in a result set
  1019.     *
  1020.     * @param int    $rownum    number of the row where the data can be found
  1021.     * @return mixed MDB2_OK on success, a MDB2 error on failure
  1022.     * @access public
  1023.     */
  1024.     function seek($rownum = 0)
  1025.     {
  1026.         if ($this->rownum != ($rownum - 1&& !@mysqli_data_seek($this->result$rownum)) {
  1027.             if (is_null($this->result)) {
  1028.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1029.                     'seek: resultset has already been freed');
  1030.             }
  1031.             return $this->db->raiseError(MDB2_ERROR_INVALIDnullnull,
  1032.                 'seek: tried to seek to an invalid row number ('.$rownum.')');
  1033.         }
  1034.         $this->rownum $rownum - 1;
  1035.         return MDB2_OK;
  1036.     }
  1037.  
  1038.     // }}}
  1039.     // {{{ valid()
  1040.  
  1041.     /**
  1042.     * check if the end of the result set has been reached
  1043.     *
  1044.     * @return mixed true or false on sucess, a MDB2 error on failure
  1045.     * @access public
  1046.     */
  1047.     function valid()
  1048.     {
  1049.         $numrows $this->numRows();
  1050.         if (PEAR::isError($numrows)) {
  1051.             return $numrows;
  1052.         }
  1053.         return $this->rownum ($numrows - 1);
  1054.     }
  1055.  
  1056.     // }}}
  1057.     // {{{ numRows()
  1058.  
  1059.     /**
  1060.     * returns the number of rows in a result object
  1061.     *
  1062.     * @return mixed MDB2 Error Object or the number of rows
  1063.     * @access public
  1064.     */
  1065.     function numRows()
  1066.     {
  1067.         $rows @mysqli_num_rows($this->result);
  1068.         if (is_null($rows)) {
  1069.             if (is_null($this->result)) {
  1070.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1071.                     'numRows: resultset has already been freed');
  1072.             }
  1073.             return $this->raiseError();
  1074.         }
  1075.         return $rows;
  1076.     }
  1077. }
  1078.  
  1079. class MDB2_Statement_mysqli extends MDB2_Statement_Common
  1080. {
  1081.     // {{{ _execute()
  1082.  
  1083.     /**
  1084.      * Execute a prepared query statement helper method.
  1085.      *
  1086.      * @param mixed $result_class string which specifies which result class to use
  1087.      * @param mixed $result_wrap_class string which specifies which class to wrap results in
  1088.      * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
  1089.      * @access private
  1090.      */
  1091.     function &_execute($result_class = true$result_wrap_class = false)
  1092.     {
  1093.         $this->db->last_query = $this->query;
  1094.         $this->db->debug($this->query'execute');
  1095.         if ($this->db->getOption('disable_query')) {
  1096.             if ($this->is_manip{
  1097.                 $return = 0;
  1098.                 return $return;
  1099.             }
  1100.             $null = null;
  1101.             return $null;
  1102.         }
  1103.  
  1104.         $connection $this->db->getConnection();
  1105.         if (PEAR::isError($connection)) {
  1106.             return $connection;
  1107.         }
  1108.  
  1109.         if (!empty($this->values)) {
  1110.             $parameters = array(0 => $this->statement1 => '');
  1111.             $lobs = array();
  1112.             $i = 0;
  1113.             foreach ($this->values as $parameter => $value{
  1114.                 $type array_key_exists($parameter$this->types$this->types[$parameter: null;
  1115.                 if (is_resource($value|| $type == 'clob' || $type == 'blob'{
  1116.                     $parameters[= null;
  1117.                     $parameters[1].= 'b';
  1118.                     $lobs[$i$parameter;
  1119.                 else {
  1120.                     $parameters[$this->db->quote($value$typefalse);
  1121.                     $parameters[1].= $this->db->datatype->mapPrepareDatatype($type);
  1122.                 }
  1123.                 ++$i;
  1124.             }
  1125.  
  1126.             $result @call_user_func_array('mysqli_stmt_bind_param'$parameters);
  1127.             if ($result === false{
  1128.                 $err =$this->db->raiseError();
  1129.                 return $err;
  1130.             }
  1131.  
  1132.             foreach ($lobs as $i => $parameter{
  1133.                 $value $this->values[$parameter];
  1134.                 $close = false;
  1135.                 if (!is_resource($value)) {
  1136.                     $close = true;
  1137.                     if (preg_match('/^(\w+:\/\/)(.*)$/'$value$match)) {
  1138.                         if ($match[1== 'file://'{
  1139.                             $value $match[2];
  1140.                         }
  1141.                         $value @fopen($value'r');
  1142.                     else {
  1143.                         $fp @tmpfile();
  1144.                         @fwrite($fp$value);
  1145.                         @rewind($fp);
  1146.                         $value $fp;
  1147.                     }
  1148.                 }
  1149.                 while (!@feof($value)) {
  1150.                     $data @fread($value$this->db->options['lob_buffer_length']);
  1151.                     @mysqli_stmt_send_long_data($this->statement$i$data);
  1152.                 }
  1153.                 if ($close{
  1154.                     @fclose($value);
  1155.                 }
  1156.             }
  1157.         }
  1158.  
  1159.         if (!@mysqli_stmt_execute($this->statement)) {
  1160.             $err =$this->db->raiseError();
  1161.             return $err;
  1162.         }
  1163.  
  1164.         if ($this->is_manip{
  1165.             $affected_rows mysqli_stmt_affected_rows($this->statement);
  1166.             return $affected_rows;
  1167.         }
  1168.  
  1169.         if ($this->db->options['result_buffering']{
  1170.             mysqli_stmt_store_result($this->statement);
  1171.         }
  1172.  
  1173.         $result &= $this->db->_wrapResult($result$this->types,
  1174.             $result_class$result_wrap_class);
  1175.         return $result;
  1176.     }
  1177.  
  1178.     // }}}
  1179.  
  1180.     // }}}
  1181.  
  1182.     // }}}
  1183.     // {{{ free()
  1184.  
  1185.     /**
  1186.      * Release resources allocated for the specified prepared query.
  1187.      *
  1188.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1189.      * @access public
  1190.      */
  1191.     function free()
  1192.     {
  1193.         if (!@mysqli_stmt_close($this->statement)) {
  1194.             return $this->db->raiseError();
  1195.         }
  1196.         return MDB2_OK;
  1197.     }
  1198. }
  1199. ?>

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