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.62 2005/12/30 11:00:49 lsmith Exp $
  47. //
  48.  
  49. /**
  50.  * MDB2 MySQL driver
  51.  *
  52.  * @package MDB2
  53.  * @category Database
  54.  * @author  Lukas Smith <smith@pooteeweet.org>
  55.  */
  56. class MDB2_Driver_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.     // {{{ connect()
  297.  
  298.     /**
  299.      * Connect to the database
  300.      *
  301.      * @return true on success, MDB2 Error Object on failure
  302.      */
  303.     function connect()
  304.     {
  305.         if (is_object($this->connection)) {
  306.             if (count(array_diff($this->connected_dsn$this->dsn)) == 0{
  307.                 return MDB2_OK;
  308.             }
  309.             $this->connection = 0;
  310.         }
  311.  
  312.         if (!PEAR::loadExtension($this->phptype)) {
  313.             return $this->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  314.                 'connect: extension '.$this->phptype.' is not compiled into PHP');
  315.         }
  316.  
  317.         @ini_set('track_errors'true);
  318.         $php_errormsg '';
  319.  
  320.         if ($this->options['ssl']{
  321.             $init @mysqli_init();
  322.             @mysqli_ssl_set(
  323.                 $init,
  324.                 empty($this->dsn['key'])    ? null : $this->dsn['key'],
  325.                 empty($this->dsn['cert'])   ? null : $this->dsn['cert'],
  326.                 empty($this->dsn['ca'])     ? null : $this->dsn['ca'],
  327.                 empty($this->dsn['capath']? null : $this->dsn['capath'],
  328.                 empty($this->dsn['cipher']? null : $this->dsn['cipher']
  329.             );
  330.             if ($connection @mysqli_real_connect(
  331.                     $init,
  332.                     $this->dsn['hostspec'],
  333.                     $this->dsn['username'],
  334.                     $this->dsn['password'],
  335.                     $this->database_name,
  336.                     $this->dsn['port'],
  337.                     $this->dsn['socket']))
  338.             {
  339.                 $connection $init;
  340.             }
  341.         else {
  342.             $connection @mysqli_connect(
  343.                 $this->dsn['hostspec'],
  344.                 $this->dsn['username'],
  345.                 $this->dsn['password'],
  346.                 $this->database_name,
  347.                 $this->dsn['port'],
  348.                 $this->dsn['socket']
  349.             );
  350.         }
  351.  
  352.         @ini_restore('track_errors');
  353.  
  354.         if (!$connection{
  355.             if (($err @mysqli_connect_error()) != ''{
  356.                 return $this->raiseError(MDB2_ERROR_CONNECT_FAILEDnullnull$err);
  357.             else {
  358.                 return $this->raiseError(MDB2_ERROR_CONNECT_FAILEDnullnull$php_errormsg);
  359.             }
  360.         }
  361.  
  362.         $this->connection $connection;
  363.         $this->connected_dsn $this->dsn;
  364.         $this->connected_database_name $this->database_name;
  365.         $this->dbsyntax $this->dsn['dbsyntax'$this->dsn['dbsyntax'$this->phptype;
  366.  
  367.         $this->supported['transactions'= false;
  368.         if ($this->options['default_table_type']{
  369.             switch (strtoupper($this->options['default_table_type'])) {
  370.             case 'BERKELEYDB':
  371.                 $this->options['default_table_type''BDB';
  372.             case 'BDB':
  373.             case 'INNODB':
  374.             case 'GEMINI':
  375.                 $this->supported['transactions'= true;
  376.                 break;
  377.             case 'HEAP':
  378.             case 'ISAM':
  379.             case 'MERGE':
  380.             case 'MRG_MYISAM':
  381.             case 'MYISAM':
  382.                 break;
  383.             default:
  384.                 $this->warnings[$default_table_type.
  385.                     ' is not a supported default table type';
  386.             }
  387.         }
  388.  
  389.         if ($this->options['use_transactions'&& !$this->supports('transactions')) {
  390.             $this->warnings[$this->options['default_table_type'].
  391.                 ' is not a transaction-safe default table type; switched to INNODB';
  392.             $this->options['default_table_type''INNODB';
  393.             $this->supported['transactions'= true;
  394.         }
  395.  
  396.         $this->supported['sub_selects'= false;
  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.         return MDB2_OK;
  406.     }
  407.  
  408.     // }}}
  409.     // {{{ disconnect()
  410.  
  411.     /**
  412.      * Log out and disconnect from the database.
  413.      *
  414.      * @return mixed true on success, false if not connected and error
  415.      *                 object on error
  416.      * @access public
  417.      */
  418.     function disconnect($force = true)
  419.     {
  420.         if (is_object($this->connection)) {
  421.             if ($this->in_transaction{
  422.                 $this->rollback();
  423.             }
  424.             if ($force{
  425.                 @mysqli_close($this->connection);
  426.             }
  427.             $this->connection = 0;
  428.             $this->in_transaction = false;
  429.         }
  430.         return MDB2_OK;
  431.     }
  432.  
  433.     // }}}
  434.     // {{{ _doQuery()
  435.  
  436.     /**
  437.      * Execute a query
  438.      * @param string $query  query
  439.      * @param boolean $is_manip  if the query is a manipulation query
  440.      * @param resource $connection 
  441.      * @param string $database_name 
  442.      * @return result or error object
  443.      * @access protected
  444.      */
  445.     function _doQuery($query$is_manip = false$connection = null$database_name = null)
  446.     {
  447.         $this->last_query $query;
  448.         $this->debug($query'query');
  449.         if ($this->options['disable_query']{
  450.             if ($is_manip{
  451.                 return 0;
  452.             }
  453.             return null;
  454.         }
  455.  
  456.         if (is_null($connection)) {
  457.             $connection $this->getConnection();
  458.             if (PEAR::isError($connection)) {
  459.                 return $connection;
  460.             }
  461.         }
  462.         if (is_null($database_name)) {
  463.             $database_name $this->database_name;
  464.         }
  465.  
  466.         if ($database_name{
  467.             if ($database_name != $this->connected_database_name{
  468.                 if (!@mysqli_select_db($connection$database_name)) {
  469.                     return $this->raiseError();
  470.                 }
  471.                 $this->connected_database_name $database_name;
  472.             }
  473.         }
  474.  
  475.         $function $this->options['result_buffering']
  476.             ? 'mysqli_query' 'mysqli_unbuffered_query';
  477.         $result @$function($connection$query);
  478.         if (!$result{
  479.             return $this->raiseError();
  480.         }
  481.  
  482.         return $result;
  483.     }
  484.  
  485.     // }}}
  486.     // {{{ _affectedRows()
  487.  
  488.     /**
  489.      * returns the number of rows affected
  490.      *
  491.      * @param resource $result 
  492.      * @param resource $connection 
  493.      * @return mixed MDB2 Error Object or the number of rows affected
  494.      * @access private
  495.      */
  496.     function _affectedRows($connection$result = null)
  497.     {
  498.         if (is_null($connection)) {
  499.             $connection $this->getConnection();
  500.             if (PEAR::isError($connection)) {
  501.                 return $connection;
  502.             }
  503.         }
  504.         return mysqli_affected_rows($connection);
  505.     }
  506.  
  507.     // }}}
  508.     // {{{ _modifyQuery()
  509.  
  510.     /**
  511.      * Changes a query string for various DBMS specific reasons
  512.      *
  513.      * @param string $query  query to modify
  514.      * @return the new (modified) query
  515.      * @access protected
  516.      */
  517.     function _modifyQuery($query$is_manip$limit$offset)
  518.     {
  519.         if ($limit > 0
  520.             && !preg_match('/LIMIT\s*\d(\s*(,|OFFSET)\s*\d+)?/i'$query)
  521.         {
  522.             $query rtrim($query);
  523.             if (substr($query-1== ';'{
  524.                 $query substr($query0-1);
  525.             }
  526.             if ($is_manip{
  527.                 return $query . " LIMIT $limit";
  528.             else {
  529.                 return $query . " LIMIT $offset$limit";
  530.             }
  531.         }
  532.         return $query;
  533.     }
  534.  
  535.     // }}}
  536.     // {{{ getServerVersion()
  537.  
  538.     /**
  539.      * return version information about the server
  540.      *
  541.      * @param string     $native  determines if the raw version string should be returned
  542.      * @return mixed array with versoin information or row string
  543.      * @access public
  544.      */
  545.     function getServerVersion($native = false)
  546.     {
  547.         $connection $this->getConnection();
  548.         if (PEAR::isError($connection)) {
  549.             return $connection;
  550.         }
  551.         $server_info mysqli_get_server_info($connection);
  552.         if (!$native{
  553.             $tmp explode('.'$server_info);
  554.             $tmp2 explode('-'@$tmp[2]);
  555.             $server_info = array(
  556.                 'major' => @$tmp[0],
  557.                 'minor' => @$tmp[1],
  558.                 'patch' => @$tmp2[0],
  559.                 'extra' => @$tmp2[1],
  560.                 'native' => $server_info,
  561.             );
  562.         }
  563.         return $server_info;
  564.     }
  565.  
  566.     // }}}
  567.     // {{{ prepare()
  568.  
  569.     /**
  570.      * Prepares a query for multiple execution with execute().
  571.      * With some database backends, this is emulated.
  572.      * prepare() requires a generic query as string like
  573.      * 'INSERT INTO numbers VALUES(?,?)' or
  574.      * 'INSERT INTO numbers VALUES(:foo,:bar)'.
  575.      * The ? and :[a-zA-Z] and  are placeholders which can be set using
  576.      * bindParam() and the query can be send off using the execute() method.
  577.      *
  578.      * @param string $query the query to prepare
  579.      * @param mixed   $types  array that contains the types of the placeholders
  580.      * @param mixed   $result_types  array that contains the types of the columns in
  581.      *                         the result set, if set to MDB2_PREPARE_MANIP the
  582.                               query is handled as a manipulation query
  583.      * @return mixed resource handle for the prepared query on success, a MDB2
  584.      *         error on failure
  585.      * @access public
  586.      * @see bindParam, execute
  587.      */
  588.     function &prepare($query$types = null$result_types = null)
  589.     {
  590.         if ($result_types !== MDB2_PREPARE_MANIP{
  591.             $obj =parent::prepare($query$types$result_types);
  592.             return $obj;
  593.         }
  594.         $is_manip = true;
  595.         $query $this->_modifyQuery($query$is_manip$this->row_limit$this->row_offset);
  596.         $this->debug($query'prepare');
  597.         $placeholder_type_guess $placeholder_type = null;
  598.         $question '?';
  599.         $colon ':';
  600.         $position = 0;
  601.         while ($position strlen($query)) {
  602.             $q_position strpos($query$question$position);
  603.             $c_position strpos($query$colon$position);
  604.             if ($q_position && $c_position{
  605.                 $p_position min($q_position$c_position);
  606.             elseif ($q_position{
  607.                 $p_position $q_position;
  608.             elseif ($c_position{
  609.                 $p_position $c_position;
  610.             else {
  611.                 break;
  612.             }
  613.             if (is_null($placeholder_type)) {
  614.                 $placeholder_type_guess $query[$p_position];
  615.             }
  616.             if (is_int($quote strpos($query"'"$position)) && $quote $p_position{
  617.                 if (!is_int($end_quote strpos($query"'"$quote + 1))) {
  618.                     $err =$this->raiseError(MDB2_ERROR_SYNTAXnullnull,
  619.                         'prepare: query with an unterminated text string specified');
  620.                     return $err;
  621.                 }
  622.                 switch ($this->escape_quotes{
  623.                 case '':
  624.                 case "'":
  625.                     $position $end_quote + 1;
  626.                     break;
  627.                 default:
  628.                     if ($end_quote == $quote + 1{
  629.                         $position $end_quote + 1;
  630.                     else {
  631.                         if ($query[$end_quote-1== $this->escape_quotes{
  632.                             $position $end_quote;
  633.                         else {
  634.                             $position $end_quote + 1;
  635.                         }
  636.                     }
  637.                     break;
  638.                 }
  639.             elseif ($query[$position== $placeholder_type_guess{
  640.                 if ($placeholder_type_guess == '?'{
  641.                     break;
  642.                 }
  643.                 if (is_null($placeholder_type)) {
  644.                     $placeholder_type $query[$p_position];
  645.                     $question $colon $placeholder_type;
  646.                 }
  647.                 $name preg_replace('/^.{'.($position+1).'}([a-z0-9_]+).*$/si''\\1'$query);
  648.                 if ($name === ''{
  649.                     $err =$this->raiseError(MDB2_ERROR_SYNTAXnullnull,
  650.                         'prepare: named parameter with an empty name');
  651.                     return $err;
  652.                 }
  653.                 $query substr_replace($query'?'$positionstrlen($name)+1);
  654.                 $position $p_position + 1;
  655.             else {
  656.                 $position $p_position;
  657.             }
  658.         }
  659.         $connection $this->getConnection();
  660.         if (PEAR::isError($connection)) {
  661.             return $connection;
  662.         }
  663.         $statement @mysqli_prepare($connection$query);
  664.         $class_name 'MDB2_Statement_'.$this->phptype;
  665.         $obj =new $class_name($this$statement$query$types$result_types$is_manip$this->row_limit$this->row_offset);
  666.         return $obj;
  667.     }
  668.  
  669.     // }}}
  670.     // {{{ replace()
  671.  
  672.     /**
  673.      * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
  674.      * query, except that if there is already a row in the table with the same
  675.      * key field values, the REPLACE query just updates its values instead of
  676.      * inserting a new row.
  677.      *
  678.      * The REPLACE type of query does not make part of the SQL standards. Since
  679.      * practically only MySQL implements it natively, this type of query is
  680.      * emulated through this method for other DBMS using standard types of
  681.      * queries inside a transaction to assure the atomicity of the operation.
  682.      *
  683.      * @access public
  684.      *
  685.      * @param string $table name of the table on which the REPLACE query will
  686.      *   be executed.
  687.      * @param array $fields associative array that describes the fields and the
  688.      *   values that will be inserted or updated in the specified table. The
  689.      *   indexes of the array are the names of all the fields of the table. The
  690.      *   values of the array are also associative arrays that describe the
  691.      *   values and other properties of the table fields.
  692.      *
  693.      *   Here follows a list of field properties that need to be specified:
  694.      *
  695.      *     value:
  696.      *           Value to be assigned to the specified field. This value may be
  697.      *           of specified in database independent type format as this
  698.      *           function can perform the necessary datatype conversions.
  699.      *
  700.      *     Default:
  701.      *           this property is required unless the Null property
  702.      *           is set to 1.
  703.      *
  704.      *     type
  705.      *           Name of the type of the field. Currently, all types Metabase
  706.      *           are supported except for clob and blob.
  707.      *
  708.      *     Default: no type conversion
  709.      *
  710.      *     null
  711.      *           Boolean property that indicates that the value for this field
  712.      *           should be set to null.
  713.      *
  714.      *           The default value for fields missing in INSERT queries may be
  715.      *           specified the definition of a table. Often, the default value
  716.      *           is already null, but since the REPLACE may be emulated using
  717.      *           an UPDATE query, make sure that all fields of the table are
  718.      *           listed in this function argument array.
  719.      *
  720.      *     Default: 0
  721.      *
  722.      *     key
  723.      *           Boolean property that indicates that this field should be
  724.      *           handled as a primary key or at least as part of the compound
  725.      *           unique index of the table that will determine the row that will
  726.      *           updated if it exists or inserted a new row otherwise.
  727.      *
  728.      *           This function will fail if no key field is specified or if the
  729.      *           value of a key field is set to null because fields that are
  730.      *           part of unique index they may not be null.
  731.      *
  732.      *     Default: 0
  733.      *
  734.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  735.      */
  736.     function replace($table$fields)
  737.     {
  738.         $count count($fields);
  739.         $query $values '';
  740.         $keys $colnum = 0;
  741.         for (reset($fields)$colnum $countnext($fields)$colnum++{
  742.             $name key($fields);
  743.             if ($colnum > 0{
  744.                 $query .= ',';
  745.                 $values.= ',';
  746.             }
  747.             $query.= $name;
  748.             if (isset($fields[$name]['null']&& $fields[$name]['null']{
  749.                 $value 'NULL';
  750.             else {
  751.                 $value $this->quote($fields[$name]['value']$fields[$name]['type']);
  752.             }
  753.             $values.= $value;
  754.             if (isset($fields[$name]['key']&& $fields[$name]['key']{
  755.                 if ($value === 'NULL'{
  756.                     return $this->raiseError(MDB2_ERROR_CANNOT_REPLACEnullnull,
  757.                         'replace: key value '.$name.' may not be NULL');
  758.                 }
  759.                 $keys++;
  760.             }
  761.         }
  762.         if ($keys == 0{
  763.             return $this->raiseError(MDB2_ERROR_CANNOT_REPLACEnullnull,
  764.                 'replace: not specified which fields are keys');
  765.         }
  766.  
  767.         $connection $this->getConnection();
  768.         if (PEAR::isError($connection)) {
  769.             return $connection;
  770.         }
  771.  
  772.         $query = "REPLACE INTO $table ($query) VALUES ($values)";
  773.         $this->last_query $query;
  774.         $this->debug($query'query');
  775.         $result $this->_doQuery($querytrue$connection);
  776.         if (PEAR::isError($result)) {
  777.             return $result;
  778.         }
  779.         return $this->_affectedRows($connection$result);
  780.     }
  781.  
  782.     // }}}
  783.     // {{{ nextID()
  784.  
  785.     /**
  786.      * returns the next free id of a sequence
  787.      *
  788.      * @param string $seq_name name of the sequence
  789.      * @param boolean $ondemand when true the seqence is
  790.      *                           automatic created, if it
  791.      *                           not exists
  792.      *
  793.      * @return mixed MDB2 Error Object or id
  794.      * @access public
  795.      */
  796.     function nextID($seq_name$ondemand = true)
  797.     {
  798.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  799.         $seqcol_name $this->quoteIdentifier($this->options['seqcol_name']true);
  800.         $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
  801.         $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  802.         $result $this->_doQuery($querytrue);
  803.         $this->popExpect();
  804.         if (PEAR::isError($result)) {
  805.             if ($ondemand && $result->getCode(== MDB2_ERROR_NOSUCHTABLE{
  806.                 $this->loadModule('Manager');
  807.                 // Since we are creating the sequence on demand
  808.                 // we know the first id = 1 so initialize the
  809.                 // sequence at 2
  810.                 $result $this->manager->createSequence($seq_name2);
  811.                 if (PEAR::isError($result)) {
  812.                     return $this->raiseError(MDB2_ERRORnullnull,
  813.                         'nextID: on demand sequence '.$seq_name.' could not be created');
  814.                 else {
  815.                     // First ID of a newly created sequence is 1
  816.                     return 1;
  817.                 }
  818.             }
  819.             return $result;
  820.         }
  821.         $value $this->lastInsertID();
  822.         if (is_numeric($value)) {
  823.             $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
  824.             $result $this->_doQuery($querytrue);
  825.             if (PEAR::isError($result)) {
  826.                 $this->warnings['nextID: could not delete previous sequence table values from '.$seq_name;
  827.             }
  828.         }
  829.         return $value;
  830.     }
  831.  
  832.     // }}}
  833.     // {{{ lastInsertID()
  834.  
  835.     /**
  836.      * returns the autoincrement ID if supported or $id
  837.      *
  838.      * @param mixed $id value as returned by getBeforeId()
  839.      * @param string $table name of the table into which a new row was inserted
  840.      * @return mixed MDB2 Error Object or id
  841.      * @access public
  842.      */
  843.     function lastInsertID($table = null$field = null)
  844.     {
  845.         $connection $this->getConnection();
  846.         if (PEAR::isError($connection)) {
  847.             return $connection;
  848.         }
  849.         $value @mysqli_insert_id($connection);
  850.         if (!$value{
  851.             return $this->raiseError();
  852.         }
  853.         return $value;
  854.     }
  855.  
  856.     // }}}
  857.     // {{{ currID()
  858.  
  859.     /**
  860.      * returns the current id of a sequence
  861.      *
  862.      * @param string $seq_name name of the sequence
  863.      * @return mixed MDB2 Error Object or id
  864.      * @access public
  865.      */
  866.     function currID($seq_name)
  867.     {
  868.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  869.         $seqcol_name $this->quoteIdentifier($this->options['seqcol_name']true);
  870.         $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
  871.         return $this->queryOne($query'integer');
  872.     }
  873. }
  874.  
  875. class MDB2_Result_mysqli extends MDB2_Result_Common
  876. {
  877.     // }}}
  878.     // {{{ fetchRow()
  879.  
  880.     /**
  881.      * Fetch a row and insert the data into an existing array.
  882.      *
  883.      * @param int       $fetchmode  how the array data should be indexed
  884.      * @param int    $rownum    number of the row where the data can be found
  885.      * @return int data array on success, a MDB2 error on failure
  886.      * @access public
  887.      */
  888.     function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT$rownum = null)
  889.     {
  890.         if (!is_null($rownum)) {
  891.             $seek $this->seek($rownum);
  892.             if (PEAR::isError($seek)) {
  893.                 return $seek;
  894.             }
  895.         }
  896.         if ($fetchmode == MDB2_FETCHMODE_DEFAULT{
  897.             $fetchmode $this->db->fetchmode;
  898.         }
  899.         if ($fetchmode MDB2_FETCHMODE_ASSOC{
  900.             $row @mysqli_fetch_assoc($this->result);
  901.             if (is_array($row)
  902.                 && $this->db->options['portability'MDB2_PORTABILITY_FIX_CASE
  903.             {
  904.                 $row array_change_key_case($row$this->db->options['field_case']);
  905.             }
  906.         else {
  907.            $row @mysqli_fetch_row($this->result);
  908.         }
  909.  
  910.         if (!$row{
  911.             if (is_null($this->result)) {
  912.                 $err =$this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  913.                     'fetchRow: resultset has already been freed');
  914.                 return $err;
  915.             }
  916.             $null = null;
  917.             return $null;
  918.         }
  919.         if ($this->db->options['portability'MDB2_PORTABILITY_EMPTY_TO_NULL{
  920.             $this->db->_fixResultArrayValues($rowMDB2_PORTABILITY_EMPTY_TO_NULL);
  921.         }
  922.         if (!empty($this->values)) {
  923.             $this->_assignBindColumns($row);
  924.         }
  925.         if (!empty($this->types)) {
  926.             $row $this->db->datatype->convertResultRow($this->types$row);
  927.         }
  928.         if ($fetchmode === MDB2_FETCHMODE_OBJECT{
  929.             $object_class $this->db->options['fetch_class'];
  930.             if ($object_class == 'stdClass'{
  931.                 $row = (object) $row;
  932.             else {
  933.                 $row &new $object_class($row);
  934.             }
  935.         }
  936.         ++$this->rownum;
  937.         return $row;
  938.     }
  939.  
  940.     // }}}
  941.     // {{{ _getColumnNames()
  942.  
  943.     /**
  944.      * Retrieve the names of columns returned by the DBMS in a query result.
  945.      *
  946.      * @return mixed                an associative array variable
  947.      *                               that will hold the names of columns. The
  948.      *                               indexes of the array are the column names
  949.      *                               mapped to lower case and the values are the
  950.      *                               respective numbers of the columns starting
  951.      *                               from 0. Some DBMS may not return any
  952.      *                               columns when the result set does not
  953.      *                               contain any rows.
  954.      *
  955.      *                               a MDB2 error on failure
  956.      * @access private
  957.      */
  958.     function _getColumnNames()
  959.     {
  960.         $columns = array();
  961.         $numcols $this->numCols();
  962.         if (PEAR::isError($numcols)) {
  963.             return $numcols;
  964.         }
  965.         for ($column = 0; $column $numcols$column++{
  966.             $column_info @mysqli_fetch_field_direct($this->result$column);
  967.             $columns[$column_info->name$column;
  968.         }
  969.         if ($this->db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  970.             $columns array_change_key_case($columns$this->db->options['field_case']);
  971.         }
  972.         return $columns;
  973.     }
  974.  
  975.     // }}}
  976.     // {{{ numCols()
  977.  
  978.     /**
  979.      * Count the number of columns returned by the DBMS in a query result.
  980.      *
  981.      * @return mixed integer value with the number of columns, a MDB2 error
  982.      *                        on failure
  983.      * @access public
  984.      */
  985.     function numCols()
  986.     {
  987.         $cols @mysqli_num_fields($this->result);
  988.         if (is_null($cols)) {
  989.             if (is_null($this->result)) {
  990.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  991.                     'numCols: resultset has already been freed');
  992.             }
  993.             return $this->db->raiseError();
  994.         }
  995.         return $cols;
  996.     }
  997.  
  998.     // }}}
  999.     // {{{ free()
  1000.  
  1001.     /**
  1002.      * Free the internal resources associated with result.
  1003.      *
  1004.      * @return boolean true on success, false if result is invalid
  1005.      * @access public
  1006.      */
  1007.     function free()
  1008.     {
  1009.         @mysqli_free_result($this->result);
  1010.         $this->result = null;
  1011.         return MDB2_OK;
  1012.     }
  1013. }
  1014.  
  1015. {
  1016.     // }}}
  1017.     // {{{ seek()
  1018.  
  1019.     /**
  1020.      * seek to a specific row in a result set
  1021.      *
  1022.      * @param int    $rownum    number of the row where the data can be found
  1023.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1024.      * @access public
  1025.      */
  1026.     function seek($rownum = 0)
  1027.     {
  1028.         if ($this->rownum != ($rownum - 1&& !@mysqli_data_seek($this->result$rownum)) {
  1029.             if (is_null($this->result)) {
  1030.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1031.                     'seek: resultset has already been freed');
  1032.             }
  1033.             return $this->db->raiseError(MDB2_ERROR_INVALIDnullnull,
  1034.                 'seek: tried to seek to an invalid row number ('.$rownum.')');
  1035.         }
  1036.         $this->rownum $rownum - 1;
  1037.         return MDB2_OK;
  1038.     }
  1039.  
  1040.     // }}}
  1041.     // {{{ valid()
  1042.  
  1043.     /**
  1044.      * check if the end of the result set has been reached
  1045.      *
  1046.      * @return mixed true or false on sucess, a MDB2 error on failure
  1047.      * @access public
  1048.      */
  1049.     function valid()
  1050.     {
  1051.         $numrows $this->numRows();
  1052.         if (PEAR::isError($numrows)) {
  1053.             return $numrows;
  1054.         }
  1055.         return $this->rownum ($numrows - 1);
  1056.     }
  1057.  
  1058.     // }}}
  1059.     // {{{ numRows()
  1060.  
  1061.     /**
  1062.      * returns the number of rows in a result object
  1063.      *
  1064.      * @return mixed MDB2 Error Object or the number of rows
  1065.      * @access public
  1066.      */
  1067.     function numRows()
  1068.     {
  1069.         $rows @mysqli_num_rows($this->result);
  1070.         if (is_null($rows)) {
  1071.             if (is_null($this->result)) {
  1072.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1073.                     'numRows: resultset has already been freed');
  1074.             }
  1075.             return $this->raiseError();
  1076.         }
  1077.         return $rows;
  1078.     }
  1079. }
  1080.  
  1081. class MDB2_Statement_mysqli extends MDB2_Statement_Common
  1082. {
  1083.     // {{{ _execute()
  1084.  
  1085.     /**
  1086.      * Execute a prepared query statement helper method.
  1087.      *
  1088.      * @param mixed $result_class string which specifies which result class to use
  1089.      * @param mixed $result_wrap_class string which specifies which class to wrap results in
  1090.      * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
  1091.      * @access private
  1092.      */
  1093.     function &_execute($result_class = true$result_wrap_class = false)
  1094.     {
  1095.         if (!$this->is_manip{
  1096.             $result =parent::_execute($result_class$result_wrap_class);
  1097.             return $result;
  1098.         }
  1099.         $this->db->last_query = $this->query;
  1100.         $this->db->debug($this->query'execute');
  1101.         if ($this->db->getOption('disable_query')) {
  1102.             if ($this->is_manip{
  1103.                 $return = 0;
  1104.                 return $return;
  1105.             }
  1106.             $null = null;
  1107.             return $null;
  1108.         }
  1109.  
  1110.         $connection $this->db->getConnection();
  1111.         if (PEAR::isError($connection)) {
  1112.             return $connection;
  1113.         }
  1114.  
  1115.         if (!empty($this->values)) {
  1116.             $parameters = array(0 => $this->statement1 => '');
  1117.             $lobs = array();
  1118.             $i = 0;
  1119.             foreach ($this->values as $parameter => $value{
  1120.                 $type array_key_exists($parameter$this->types$this->types[$parameter: null;
  1121.                 if (is_resource($value|| $type == 'clob' || $type == 'blob'{
  1122.                     $parameters[= null;
  1123.                     $parameters[1].= 'b';
  1124.                     $lobs[$i$parameter;
  1125.                 else {
  1126.                     $parameters[$this->db->quote($value$typefalse);
  1127.                     $parameters[1].= $this->db->datatype->mapPrepareDatatype($type);
  1128.                 }
  1129.                 ++$i;
  1130.             }
  1131.  
  1132.             $result @call_user_func_array('mysqli_stmt_bind_param'$parameters);
  1133.             if ($result === false{
  1134.                 $err =$this->db->raiseError();
  1135.                 return $err;
  1136.             }
  1137.  
  1138.             foreach ($lobs as $i => $parameter{
  1139.                 $value $this->values[$parameter];
  1140.                 $close = false;
  1141.                 if (!is_resource($value)) {
  1142.                     $close = true;
  1143.                     if (preg_match('/^(\w+:\/\/)(.*)$/'$value$match)) {
  1144.                         if ($match[1== 'file://'{
  1145.                             $value $match[2];
  1146.                         }
  1147.                         $value @fopen($value'r');
  1148.                     else {
  1149.                         $fp @tmpfile();
  1150.                         @fwrite($fp$value);
  1151.                         @rewind($fp);
  1152.                         $value $fp;
  1153.                     }
  1154.                 }
  1155.                 while (!@feof($value)) {
  1156.                     $data @fread($value$this->db->options['lob_buffer_length']);
  1157.                     @mysqli_stmt_send_long_data($this->statement$i$data);
  1158.                 }
  1159.                 if ($close{
  1160.                     @fclose($value);
  1161.                 }
  1162.             }
  1163.         }
  1164.  
  1165.         if (!@mysqli_stmt_execute($this->statement)) {
  1166.             $err =$this->db->raiseError();
  1167.             return $err;
  1168.         }
  1169.  
  1170.         if ($this->is_manip{
  1171.             $affected_rows mysqli_stmt_affected_rows($this->statement);
  1172.             return $affected_rows;
  1173.         }
  1174.  
  1175.         if ($this->db->options['result_buffering']{
  1176.             mysqli_stmt_store_result($this->statement);
  1177.         }
  1178.  
  1179.         $result =$this->db->_wrapResult($this->statement$this->result_types,
  1180.             $result_class$result_wrap_class);
  1181.         return $result;
  1182.     }
  1183.  
  1184.     // }}}
  1185.  
  1186.     // }}}
  1187.  
  1188.     // }}}
  1189.     // {{{ free()
  1190.  
  1191.     /**
  1192.      * Release resources allocated for the specified prepared query.
  1193.      *
  1194.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1195.      * @access public
  1196.      */
  1197.     function free()
  1198.     {
  1199.         if (!$this->is_manip{
  1200.             return parent::free();
  1201.         }
  1202.         if (!@mysqli_stmt_close($this->statement)) {
  1203.             return $this->db->raiseError();
  1204.         }
  1205.         return MDB2_OK;
  1206.     }
  1207. }
  1208. ?>

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