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

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