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.61 2005/12/28 10:14:57 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'= 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.         if ($result_types !== MDB2_PREPARE_MANIP{
  593.             $obj =parent::prepare($query$types$result_types);
  594.             return $obj;
  595.         }
  596.         $is_manip = true;
  597.         $query $this->_modifyQuery($query$is_manip$this->row_limit$this->row_offset);
  598.         $this->debug($query'prepare');
  599.         $placeholder_type_guess $placeholder_type = null;
  600.         $question '?';
  601.         $colon ':';
  602.         $position = 0;
  603.         while ($position strlen($query)) {
  604.             $q_position strpos($query$question$position);
  605.             $c_position strpos($query$colon$position);
  606.             if ($q_position && $c_position{
  607.                 $p_position min($q_position$c_position);
  608.             elseif ($q_position{
  609.                 $p_position $q_position;
  610.             elseif ($c_position{
  611.                 $p_position $c_position;
  612.             else {
  613.                 break;
  614.             }
  615.             if (is_null($placeholder_type)) {
  616.                 $placeholder_type_guess $query[$p_position];
  617.             }
  618.             if (is_int($quote strpos($query"'"$position)) && $quote $p_position{
  619.                 if (!is_int($end_quote strpos($query"'"$quote + 1))) {
  620.                     $err =$this->raiseError(MDB2_ERROR_SYNTAXnullnull,
  621.                         'prepare: query with an unterminated text string specified');
  622.                     return $err;
  623.                 }
  624.                 switch ($this->escape_quotes{
  625.                 case '':
  626.                 case "'":
  627.                     $position $end_quote + 1;
  628.                     break;
  629.                 default:
  630.                     if ($end_quote == $quote + 1{
  631.                         $position $end_quote + 1;
  632.                     else {
  633.                         if ($query[$end_quote-1== $this->escape_quotes{
  634.                             $position $end_quote;
  635.                         else {
  636.                             $position $end_quote + 1;
  637.                         }
  638.                     }
  639.                     break;
  640.                 }
  641.             elseif ($query[$position== $placeholder_type_guess{
  642.                 if ($placeholder_type_guess == '?'{
  643.                     break;
  644.                 }
  645.                 if (is_null($placeholder_type)) {
  646.                     $placeholder_type $query[$p_position];
  647.                     $question $colon $placeholder_type;
  648.                 }
  649.                 $name preg_replace('/^.{'.($position+1).'}([a-z0-9_]+).*$/si''\\1'$query);
  650.                 if ($name === ''{
  651.                     $err =$this->raiseError(MDB2_ERROR_SYNTAXnullnull,
  652.                         'prepare: named parameter with an empty name');
  653.                     return $err;
  654.                 }
  655.                 $query substr_replace($query'?'$positionstrlen($name)+1);
  656.                 $position $p_position + 1;
  657.             else {
  658.                 $position $p_position;
  659.             }
  660.         }
  661.         $connection $this->getConnection();
  662.         if (PEAR::isError($connection)) {
  663.             return $connection;
  664.         }
  665.         $statement @mysqli_prepare($connection$query);
  666.         $class_name 'MDB2_Statement_'.$this->phptype;
  667.         $obj =new $class_name($this$statement$query$types$result_types$is_manip$this->row_limit$this->row_offset);
  668.         return $obj;
  669.     }
  670.  
  671.     // }}}
  672.     // {{{ replace()
  673.  
  674.     /**
  675.      * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
  676.      * query, except that if there is already a row in the table with the same
  677.      * key field values, the REPLACE query just updates its values instead of
  678.      * inserting a new row.
  679.      *
  680.      * The REPLACE type of query does not make part of the SQL standards. Since
  681.      * practically only MySQL implements it natively, this type of query is
  682.      * emulated through this method for other DBMS using standard types of
  683.      * queries inside a transaction to assure the atomicity of the operation.
  684.      *
  685.      * @access public
  686.      *
  687.      * @param string $table name of the table on which the REPLACE query will
  688.      *   be executed.
  689.      * @param array $fields associative array that describes the fields and the
  690.      *   values that will be inserted or updated in the specified table. The
  691.      *   indexes of the array are the names of all the fields of the table. The
  692.      *   values of the array are also associative arrays that describe the
  693.      *   values and other properties of the table fields.
  694.      *
  695.      *   Here follows a list of field properties that need to be specified:
  696.      *
  697.      *     value:
  698.      *           Value to be assigned to the specified field. This value may be
  699.      *           of specified in database independent type format as this
  700.      *           function can perform the necessary datatype conversions.
  701.      *
  702.      *     Default:
  703.      *           this property is required unless the Null property
  704.      *           is set to 1.
  705.      *
  706.      *     type
  707.      *           Name of the type of the field. Currently, all types Metabase
  708.      *           are supported except for clob and blob.
  709.      *
  710.      *     Default: no type conversion
  711.      *
  712.      *     null
  713.      *           Boolean property that indicates that the value for this field
  714.      *           should be set to null.
  715.      *
  716.      *           The default value for fields missing in INSERT queries may be
  717.      *           specified the definition of a table. Often, the default value
  718.      *           is already null, but since the REPLACE may be emulated using
  719.      *           an UPDATE query, make sure that all fields of the table are
  720.      *           listed in this function argument array.
  721.      *
  722.      *     Default: 0
  723.      *
  724.      *     key
  725.      *           Boolean property that indicates that this field should be
  726.      *           handled as a primary key or at least as part of the compound
  727.      *           unique index of the table that will determine the row that will
  728.      *           updated if it exists or inserted a new row otherwise.
  729.      *
  730.      *           This function will fail if no key field is specified or if the
  731.      *           value of a key field is set to null because fields that are
  732.      *           part of unique index they may not be null.
  733.      *
  734.      *     Default: 0
  735.      *
  736.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  737.      */
  738.     function replace($table$fields)
  739.     {
  740.         $count count($fields);
  741.         $query $values '';
  742.         $keys $colnum = 0;
  743.         for (reset($fields)$colnum $countnext($fields)$colnum++{
  744.             $name key($fields);
  745.             if ($colnum > 0{
  746.                 $query .= ',';
  747.                 $values.= ',';
  748.             }
  749.             $query.= $name;
  750.             if (isset($fields[$name]['null']&& $fields[$name]['null']{
  751.                 $value 'NULL';
  752.             else {
  753.                 $value $this->quote($fields[$name]['value']$fields[$name]['type']);
  754.             }
  755.             $values.= $value;
  756.             if (isset($fields[$name]['key']&& $fields[$name]['key']{
  757.                 if ($value === 'NULL'{
  758.                     return $this->raiseError(MDB2_ERROR_CANNOT_REPLACEnullnull,
  759.                         'replace: key value '.$name.' may not be NULL');
  760.                 }
  761.                 $keys++;
  762.             }
  763.         }
  764.         if ($keys == 0{
  765.             return $this->raiseError(MDB2_ERROR_CANNOT_REPLACEnullnull,
  766.                 'replace: not specified which fields are keys');
  767.         }
  768.  
  769.         $connection $this->getConnection();
  770.         if (PEAR::isError($connection)) {
  771.             return $connection;
  772.         }
  773.  
  774.         $query = "REPLACE INTO $table ($query) VALUES ($values)";
  775.         $this->last_query $query;
  776.         $this->debug($query'query');
  777.         $result $this->_doQuery($querytrue$connection);
  778.         if (PEAR::isError($result)) {
  779.             return $result;
  780.         }
  781.         return $this->_affectedRows($connection$result);
  782.     }
  783.  
  784.     // }}}
  785.     // {{{ nextID()
  786.  
  787.     /**
  788.      * returns the next free id of a sequence
  789.      *
  790.      * @param string $seq_name name of the sequence
  791.      * @param boolean $ondemand when true the seqence is
  792.      *                           automatic created, if it
  793.      *                           not exists
  794.      *
  795.      * @return mixed MDB2 Error Object or id
  796.      * @access public
  797.      */
  798.     function nextID($seq_name$ondemand = true)
  799.     {
  800.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  801.         $seqcol_name $this->quoteIdentifier($this->options['seqcol_name']true);
  802.         $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
  803.         $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  804.         $result $this->_doQuery($querytrue);
  805.         $this->popExpect();
  806.         if (PEAR::isError($result)) {
  807.             if ($ondemand && $result->getCode(== MDB2_ERROR_NOSUCHTABLE{
  808.                 $this->loadModule('Manager');
  809.                 // Since we are creating the sequence on demand
  810.                 // we know the first id = 1 so initialize the
  811.                 // sequence at 2
  812.                 $result $this->manager->createSequence($seq_name2);
  813.                 if (PEAR::isError($result)) {
  814.                     return $this->raiseError(MDB2_ERRORnullnull,
  815.                         'nextID: on demand sequence '.$seq_name.' could not be created');
  816.                 else {
  817.                     // First ID of a newly created sequence is 1
  818.                     return 1;
  819.                 }
  820.             }
  821.             return $result;
  822.         }
  823.         $value $this->lastInsertID();
  824.         if (is_numeric($value)) {
  825.             $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
  826.             $result $this->_doQuery($querytrue);
  827.             if (PEAR::isError($result)) {
  828.                 $this->warnings['nextID: could not delete previous sequence table values from '.$seq_name;
  829.             }
  830.         }
  831.         return $value;
  832.     }
  833.  
  834.     // }}}
  835.     // {{{ lastInsertID()
  836.  
  837.     /**
  838.      * returns the autoincrement ID if supported or $id
  839.      *
  840.      * @param mixed $id value as returned by getBeforeId()
  841.      * @param string $table name of the table into which a new row was inserted
  842.      * @return mixed MDB2 Error Object or id
  843.      * @access public
  844.      */
  845.     function lastInsertID($table = null$field = null)
  846.     {
  847.         $connection $this->getConnection();
  848.         if (PEAR::isError($connection)) {
  849.             return $connection;
  850.         }
  851.         $value @mysqli_insert_id($connection);
  852.         if (!$value{
  853.             return $this->raiseError();
  854.         }
  855.         return $value;
  856.     }
  857.  
  858.     // }}}
  859.     // {{{ currID()
  860.  
  861.     /**
  862.      * returns the current id of a sequence
  863.      *
  864.      * @param string $seq_name name of the sequence
  865.      * @return mixed MDB2 Error Object or id
  866.      * @access public
  867.      */
  868.     function currID($seq_name)
  869.     {
  870.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  871.         $seqcol_name $this->quoteIdentifier($this->options['seqcol_name']true);
  872.         $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
  873.         return $this->queryOne($query'integer');
  874.     }
  875. }
  876.  
  877. class MDB2_Result_mysqli extends MDB2_Result_Common
  878. {
  879.     // }}}
  880.     // {{{ fetchRow()
  881.  
  882.     /**
  883.      * Fetch a row and insert the data into an existing array.
  884.      *
  885.      * @param int       $fetchmode  how the array data should be indexed
  886.      * @param int    $rownum    number of the row where the data can be found
  887.      * @return int data array on success, a MDB2 error on failure
  888.      * @access public
  889.      */
  890.     function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT$rownum = null)
  891.     {
  892.         if (!is_null($rownum)) {
  893.             $seek $this->seek($rownum);
  894.             if (PEAR::isError($seek)) {
  895.                 return $seek;
  896.             }
  897.         }
  898.         if ($fetchmode == MDB2_FETCHMODE_DEFAULT{
  899.             $fetchmode $this->db->fetchmode;
  900.         }
  901.         if ($fetchmode MDB2_FETCHMODE_ASSOC{
  902.             $row @mysqli_fetch_assoc($this->result);
  903.             if (is_array($row)
  904.                 && $this->db->options['portability'MDB2_PORTABILITY_FIX_CASE
  905.             {
  906.                 $row array_change_key_case($row$this->db->options['field_case']);
  907.             }
  908.         else {
  909.            $row @mysqli_fetch_row($this->result);
  910.         }
  911.  
  912.         if (!$row{
  913.             if (is_null($this->result)) {
  914.                 $err =$this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  915.                     'fetchRow: resultset has already been freed');
  916.                 return $err;
  917.             }
  918.             $null = null;
  919.             return $null;
  920.         }
  921.         if ($this->db->options['portability'MDB2_PORTABILITY_EMPTY_TO_NULL{
  922.             $this->db->_fixResultArrayValues($rowMDB2_PORTABILITY_EMPTY_TO_NULL);
  923.         }
  924.         if (!empty($this->values)) {
  925.             $this->_assignBindColumns($row);
  926.         }
  927.         if (!empty($this->types)) {
  928.             $row $this->db->datatype->convertResultRow($this->types$row);
  929.         }
  930.         if ($fetchmode === MDB2_FETCHMODE_OBJECT{
  931.             $object_class $this->db->options['fetch_class'];
  932.             if ($object_class == 'stdClass'{
  933.                 $row = (object) $row;
  934.             else {
  935.                 $row &new $object_class($row);
  936.             }
  937.         }
  938.         ++$this->rownum;
  939.         return $row;
  940.     }
  941.  
  942.     // }}}
  943.     // {{{ _getColumnNames()
  944.  
  945.     /**
  946.      * Retrieve the names of columns returned by the DBMS in a query result.
  947.      *
  948.      * @return mixed                an associative array variable
  949.      *                               that will hold the names of columns. The
  950.      *                               indexes of the array are the column names
  951.      *                               mapped to lower case and the values are the
  952.      *                               respective numbers of the columns starting
  953.      *                               from 0. Some DBMS may not return any
  954.      *                               columns when the result set does not
  955.      *                               contain any rows.
  956.      *
  957.      *                               a MDB2 error on failure
  958.      * @access private
  959.      */
  960.     function _getColumnNames()
  961.     {
  962.         $columns = array();
  963.         $numcols $this->numCols();
  964.         if (PEAR::isError($numcols)) {
  965.             return $numcols;
  966.         }
  967.         for ($column = 0; $column $numcols$column++{
  968.             $column_info @mysqli_fetch_field_direct($this->result$column);
  969.             $columns[$column_info->name$column;
  970.         }
  971.         if ($this->db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  972.             $columns array_change_key_case($columns$this->db->options['field_case']);
  973.         }
  974.         return $columns;
  975.     }
  976.  
  977.     // }}}
  978.     // {{{ numCols()
  979.  
  980.     /**
  981.      * Count the number of columns returned by the DBMS in a query result.
  982.      *
  983.      * @return mixed integer value with the number of columns, a MDB2 error
  984.      *                        on failure
  985.      * @access public
  986.      */
  987.     function numCols()
  988.     {
  989.         $cols @mysqli_num_fields($this->result);
  990.         if (is_null($cols)) {
  991.             if (is_null($this->result)) {
  992.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  993.                     'numCols: resultset has already been freed');
  994.             }
  995.             return $this->db->raiseError();
  996.         }
  997.         return $cols;
  998.     }
  999.  
  1000.     // }}}
  1001.     // {{{ free()
  1002.  
  1003.     /**
  1004.      * Free the internal resources associated with result.
  1005.      *
  1006.      * @return boolean true on success, false if result is invalid
  1007.      * @access public
  1008.      */
  1009.     function free()
  1010.     {
  1011.         @mysqli_free_result($this->result);
  1012.         $this->result = null;
  1013.         return MDB2_OK;
  1014.     }
  1015. }
  1016.  
  1017. {
  1018.     // }}}
  1019.     // {{{ seek()
  1020.  
  1021.     /**
  1022.      * seek to a specific row in a result set
  1023.      *
  1024.      * @param int    $rownum    number of the row where the data can be found
  1025.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1026.      * @access public
  1027.      */
  1028.     function seek($rownum = 0)
  1029.     {
  1030.         if ($this->rownum != ($rownum - 1&& !@mysqli_data_seek($this->result$rownum)) {
  1031.             if (is_null($this->result)) {
  1032.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1033.                     'seek: resultset has already been freed');
  1034.             }
  1035.             return $this->db->raiseError(MDB2_ERROR_INVALIDnullnull,
  1036.                 'seek: tried to seek to an invalid row number ('.$rownum.')');
  1037.         }
  1038.         $this->rownum $rownum - 1;
  1039.         return MDB2_OK;
  1040.     }
  1041.  
  1042.     // }}}
  1043.     // {{{ valid()
  1044.  
  1045.     /**
  1046.      * check if the end of the result set has been reached
  1047.      *
  1048.      * @return mixed true or false on sucess, a MDB2 error on failure
  1049.      * @access public
  1050.      */
  1051.     function valid()
  1052.     {
  1053.         $numrows $this->numRows();
  1054.         if (PEAR::isError($numrows)) {
  1055.             return $numrows;
  1056.         }
  1057.         return $this->rownum ($numrows - 1);
  1058.     }
  1059.  
  1060.     // }}}
  1061.     // {{{ numRows()
  1062.  
  1063.     /**
  1064.      * returns the number of rows in a result object
  1065.      *
  1066.      * @return mixed MDB2 Error Object or the number of rows
  1067.      * @access public
  1068.      */
  1069.     function numRows()
  1070.     {
  1071.         $rows @mysqli_num_rows($this->result);
  1072.         if (is_null($rows)) {
  1073.             if (is_null($this->result)) {
  1074.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1075.                     'numRows: resultset has already been freed');
  1076.             }
  1077.             return $this->raiseError();
  1078.         }
  1079.         return $rows;
  1080.     }
  1081. }
  1082.  
  1083. class MDB2_Statement_mysqli extends MDB2_Statement_Common
  1084. {
  1085.     // {{{ _execute()
  1086.  
  1087.     /**
  1088.      * Execute a prepared query statement helper method.
  1089.      *
  1090.      * @param mixed $result_class string which specifies which result class to use
  1091.      * @param mixed $result_wrap_class string which specifies which class to wrap results in
  1092.      * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
  1093.      * @access private
  1094.      */
  1095.     function &_execute($result_class = true$result_wrap_class = false)
  1096.     {
  1097.         if (!$this->is_manip{
  1098.             $result =parent::_execute($result_class$result_wrap_class);
  1099.             return $result;
  1100.         }
  1101.         $this->db->last_query = $this->query;
  1102.         $this->db->debug($this->query'execute');
  1103.         if ($this->db->getOption('disable_query')) {
  1104.             if ($this->is_manip{
  1105.                 $return = 0;
  1106.                 return $return;
  1107.             }
  1108.             $null = null;
  1109.             return $null;
  1110.         }
  1111.  
  1112.         $connection $this->db->getConnection();
  1113.         if (PEAR::isError($connection)) {
  1114.             return $connection;
  1115.         }
  1116.  
  1117.         if (!empty($this->values)) {
  1118.             $parameters = array(0 => $this->statement1 => '');
  1119.             $lobs = array();
  1120.             $i = 0;
  1121.             foreach ($this->values as $parameter => $value{
  1122.                 $type array_key_exists($parameter$this->types$this->types[$parameter: null;
  1123.                 if (is_resource($value|| $type == 'clob' || $type == 'blob'{
  1124.                     $parameters[= null;
  1125.                     $parameters[1].= 'b';
  1126.                     $lobs[$i$parameter;
  1127.                 else {
  1128.                     $parameters[$this->db->quote($value$typefalse);
  1129.                     $parameters[1].= $this->db->datatype->mapPrepareDatatype($type);
  1130.                 }
  1131.                 ++$i;
  1132.             }
  1133.  
  1134.             $result @call_user_func_array('mysqli_stmt_bind_param'$parameters);
  1135.             if ($result === false{
  1136.                 $err =$this->db->raiseError();
  1137.                 return $err;
  1138.             }
  1139.  
  1140.             foreach ($lobs as $i => $parameter{
  1141.                 $value $this->values[$parameter];
  1142.                 $close = false;
  1143.                 if (!is_resource($value)) {
  1144.                     $close = true;
  1145.                     if (preg_match('/^(\w+:\/\/)(.*)$/'$value$match)) {
  1146.                         if ($match[1== 'file://'{
  1147.                             $value $match[2];
  1148.                         }
  1149.                         $value @fopen($value'r');
  1150.                     else {
  1151.                         $fp @tmpfile();
  1152.                         @fwrite($fp$value);
  1153.                         @rewind($fp);
  1154.                         $value $fp;
  1155.                     }
  1156.                 }
  1157.                 while (!@feof($value)) {
  1158.                     $data @fread($value$this->db->options['lob_buffer_length']);
  1159.                     @mysqli_stmt_send_long_data($this->statement$i$data);
  1160.                 }
  1161.                 if ($close{
  1162.                     @fclose($value);
  1163.                 }
  1164.             }
  1165.         }
  1166.  
  1167.         if (!@mysqli_stmt_execute($this->statement)) {
  1168.             $err =$this->db->raiseError();
  1169.             return $err;
  1170.         }
  1171.  
  1172.         if ($this->is_manip{
  1173.             $affected_rows mysqli_stmt_affected_rows($this->statement);
  1174.             return $affected_rows;
  1175.         }
  1176.  
  1177.         if ($this->db->options['result_buffering']{
  1178.             mysqli_stmt_store_result($this->statement);
  1179.         }
  1180.  
  1181.         $result =$this->db->_wrapResult($this->statement$this->result_types,
  1182.             $result_class$result_wrap_class);
  1183.         return $result;
  1184.     }
  1185.  
  1186.     // }}}
  1187.  
  1188.     // }}}
  1189.  
  1190.     // }}}
  1191.     // {{{ free()
  1192.  
  1193.     /**
  1194.      * Release resources allocated for the specified prepared query.
  1195.      *
  1196.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1197.      * @access public
  1198.      */
  1199.     function free()
  1200.     {
  1201.         if (!$this->is_manip{
  1202.             return parent::free();
  1203.         }
  1204.         if (!@mysqli_stmt_close($this->statement)) {
  1205.             return $this->db->raiseError();
  1206.         }
  1207.         return MDB2_OK;
  1208.     }
  1209. }
  1210. ?>

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