MDB2
[ class tree: MDB2 ] [ index: MDB2 ] [ all elements ]

Source for file mysql.php

Documentation is available at mysql.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: mysql.php,v 1.93 2006/01/12 16:48:02 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_mysql 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 'mysql';
  72.         $this->dbsyntax 'mysql';
  73.  
  74.         $this->supported['sequences''emulated';
  75.         $this->supported['indexes'= true;
  76.         $this->supported['affected_rows'= true;
  77.         $this->supported['transactions'= false;
  78.         $this->supported['summary_functions'= true;
  79.         $this->supported['order_by_text'= true;
  80.         $this->supported['current_id''emulated';
  81.         $this->supported['limit_queries'= true;
  82.         $this->supported['LOBs'= true;
  83.         $this->supported['replace'= true;
  84.         $this->supported['sub_selects''emulated';
  85.         $this->supported['auto_increment'= true;
  86.         $this->supported['primary_key'= true;
  87.  
  88.         $this->options['default_table_type'= null;
  89.     }
  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 @mysql_errno($this->connection);
  105.             $native_msg  @mysql_error($this->connection);
  106.         else {
  107.             $native_code @mysql_errno();
  108.             $native_msg  @mysql_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 @mysql_real_escape_string($text$connection);
  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 = false)
  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.         if (!$this->destructor_registered && $this->opened_persistent{
  222.             $this->destructor_registered = true;
  223.             register_shutdown_function('MDB2_closeOpenTransactions');
  224.         }
  225.         $result $this->_doQuery('SET AUTOCOMMIT = 0'true);
  226.         if (PEAR::isError($result)) {
  227.             return $result;
  228.         }
  229.         $this->in_transaction = true;
  230.         return MDB2_OK;
  231.     }
  232.  
  233.     // }}}
  234.     // {{{ commit()
  235.  
  236.     /**
  237.      * Commit the database changes done during a transaction that is in
  238.      * progress.
  239.      *
  240.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  241.      * @access public
  242.      */
  243.     function commit()
  244.     {
  245.         $this->debug('commit transaction''commit');
  246.         if (!$this->supports('transactions')) {
  247.             return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  248.                 'commit: transactions are not in use');
  249.         }
  250.         if (!$this->in_transaction{
  251.             return $this->raiseError(MDB2_ERRORnullnull,
  252.                 'commit: transaction changes are being auto committed');
  253.         }
  254.         $result $this->_doQuery('COMMIT'true);
  255.         if (PEAR::isError($result)) {
  256.             return $result;
  257.         }
  258.         $result $this->_doQuery('SET AUTOCOMMIT = 1'true);
  259.         if (PEAR::isError($result)) {
  260.             return $result;
  261.         }
  262.         $this->in_transaction = false;
  263.         return MDB2_OK;
  264.     }
  265.  
  266.     // }}}
  267.     // {{{ rollback()
  268.  
  269.     /**
  270.      * Cancel any database changes done during a transaction that is in
  271.      * progress.
  272.      *
  273.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  274.      * @access public
  275.      */
  276.     function rollback()
  277.     {
  278.         $this->debug('rolling back transaction''rollback');
  279.         if (!$this->supports('transactions')) {
  280.             return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  281.                 'rollback: transactions are not in use');
  282.         }
  283.         if (!$this->in_transaction{
  284.             return $this->raiseError(MDB2_ERRORnullnull,
  285.                 'rollback: transactions can not be rolled back when changes are auto committed');
  286.         }
  287.         $result $this->_doQuery('ROLLBACK'true);
  288.         if (PEAR::isError($result)) {
  289.             return $result;
  290.         }
  291.         $result $this->_doQuery('SET AUTOCOMMIT = 1'true);
  292.         if (PEAR::isError($result)) {
  293.             return $result;
  294.         }
  295.         $this->in_transaction = false;
  296.         return MDB2_OK;
  297.  
  298.     }
  299.  
  300.     // }}}
  301.     // {{{ connect()
  302.  
  303.     /**
  304.      * Connect to the database
  305.      *
  306.      * @return true on success, MDB2 Error Object on failure
  307.      */
  308.     function connect()
  309.     {
  310.         if (is_resource($this->connection)) {
  311.             if (count(array_diff($this->connected_dsn$this->dsn)) == 0
  312.                 && $this->opened_persistent == $this->options['persistent']
  313.             {
  314.                 return MDB2_OK;
  315.             }
  316.             $this->disconnect(false);
  317.         }
  318.  
  319.         if (!PEAR::loadExtension($this->phptype)) {
  320.             return $this->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  321.                 'connect: extension '.$this->phptype.' is not compiled into PHP');
  322.         }
  323.  
  324.         $params = array();
  325.         if ($this->dsn['protocol'&& $this->dsn['protocol'== 'unix'{
  326.             $params[0':' $this->dsn['socket'];
  327.         else {
  328.             $params[0$this->dsn['hostspec'$this->dsn['hostspec']
  329.                          : 'localhost';
  330.             if ($this->dsn['port']{
  331.                 $params[0].= ':' $this->dsn['port'];
  332.             }
  333.         }
  334.         $params[$this->dsn['username'$this->dsn['username': null;
  335.         $params[$this->dsn['password'$this->dsn['password': null;
  336.         if (!$this->options['persistent']{
  337.             if (isset($this->dsn['new_link'])
  338.                 && ($this->dsn['new_link'== 'true' || $this->dsn['new_link'=== true)
  339.             {
  340.                 $params[= true;
  341.             else {
  342.                 $params[= false;
  343.             }
  344.         }
  345.         if (version_compare(phpversion()'4.3.0''>=')) {
  346.             $params[= isset($this->dsn['client_flags'])
  347.                 ? $this->dsn['client_flags': null;
  348.         }
  349.  
  350.         $connect_function $this->options['persistent''mysql_pconnect' 'mysql_connect';
  351.  
  352.         @ini_set('track_errors'true);
  353.         $php_errormsg '';
  354.         $connection @call_user_func_array($connect_function$params);
  355.         @ini_restore('track_errors');
  356.         if (!$connection{
  357.             if (($err @mysql_error()) != ''{
  358.                 return $this->raiseError(MDB2_ERROR_CONNECT_FAILEDnullnull$err);
  359.             else {
  360.                 return $this->raiseError(MDB2_ERROR_CONNECT_FAILEDnullnull$php_errormsg);
  361.             }
  362.         }
  363.  
  364.         $this->connection $connection;
  365.         $this->connected_dsn $this->dsn;
  366.         $this->connected_database_name '';
  367.         $this->opened_persistent $this->options['persistent'];
  368.         $this->dbsyntax $this->dsn['dbsyntax'$this->dsn['dbsyntax'$this->phptype;
  369.  
  370.         $this->supported['transactions'= false;
  371.         if ($this->options['default_table_type']{
  372.             switch (strtoupper($this->options['default_table_type'])) {
  373.             case 'BERKELEYDB':
  374.                 $this->options['default_table_type''BDB';
  375.             case 'BDB':
  376.             case 'INNODB':
  377.             case 'GEMINI':
  378.                 $this->supported['transactions'= true;
  379.                 break;
  380.             case 'HEAP':
  381.             case 'ISAM':
  382.             case 'MERGE':
  383.             case 'MRG_MYISAM':
  384.             case 'MYISAM':
  385.                 break;
  386.             default:
  387.                 $this->warnings[$default_table_type.
  388.                     ' is not a supported default table type';
  389.             }
  390.         }
  391.  
  392.         if ($this->options['use_transactions'&& !$this->supports('transactions')) {
  393.             $this->warnings[$this->options['default_table_type'].
  394.                 ' is not a transaction-safe default table type; switched to INNODB';
  395.             $this->options['default_table_type''INNODB';
  396.             $this->supported['transactions'= true;
  397.         }
  398.  
  399.         $this->supported['sub_selects'= false;
  400.         $server_info $this->getServerVersion();
  401.         if (is_array($server_info)
  402.             && ($server_info['major'> 4
  403.                 || ($server_info['major'== 4 && $server_info['minor'>= 1)
  404.             )
  405.         {
  406.             $this->supported['sub_selects'= true;
  407.         }
  408.  
  409.         return MDB2_OK;
  410.     }
  411.  
  412.     // }}}
  413.     // {{{ disconnect()
  414.  
  415.     /**
  416.      * Log out and disconnect from the database.
  417.      *
  418.      * @return mixed true on success, false if not connected and error
  419.      *                 object on error
  420.      * @access public
  421.      */
  422.     function disconnect($force = true)
  423.     {
  424.         if (is_resource($this->connection)) {
  425.             if ($this->in_transaction{
  426.                 $this->rollback();
  427.             }
  428.             if (!$this->opened_persistent || $force{
  429.                 @mysql_close($this->connection);
  430.             }
  431.             $this->connection = 0;
  432.             $this->in_transaction = false;
  433.         }
  434.         return MDB2_OK;
  435.     }
  436.  
  437.     // }}}
  438.     // {{{ _doQuery()
  439.  
  440.     /**
  441.      * Execute a query
  442.      * @param string $query  query
  443.      * @param boolean $is_manip  if the query is a manipulation query
  444.      * @param resource $connection 
  445.      * @param string $database_name 
  446.      * @return result or error object
  447.      * @access protected
  448.      */
  449.     function _doQuery($query$is_manip = false$connection = null$database_name = null)
  450.     {
  451.         $this->last_query $query;
  452.         $this->debug($query'query');
  453.         if ($this->options['disable_query']{
  454.             if ($is_manip{
  455.                 return 0;
  456.             }
  457.             return null;
  458.         }
  459.  
  460.         if (is_null($connection)) {
  461.             $connection $this->getConnection();
  462.             if (PEAR::isError($connection)) {
  463.                 return $connection;
  464.             }
  465.         }
  466.         if (is_null($database_name)) {
  467.             $database_name $this->database_name;
  468.         }
  469.  
  470.         if ($database_name{
  471.             if ($database_name != $this->connected_database_name{
  472.                 if (!@mysql_select_db($database_name$connection)) {
  473.                     return $this->raiseError();
  474.                 }
  475.                 $this->connected_database_name $database_name;
  476.             }
  477.         }
  478.  
  479.         $function $this->options['result_buffering']
  480.             ? 'mysql_query' 'mysql_unbuffered_query';
  481.         $result @$function($query$connection);
  482.         if (!$result{
  483.             return $this->raiseError();
  484.         }
  485.  
  486.         return $result;
  487.     }
  488.  
  489.     // }}}
  490.     // {{{ _affectedRows()
  491.  
  492.     /**
  493.      * returns the number of rows affected
  494.      *
  495.      * @param resource $result 
  496.      * @param resource $connection 
  497.      * @return mixed MDB2 Error Object or the number of rows affected
  498.      * @access private
  499.      */
  500.     function _affectedRows($connection$result = null)
  501.     {
  502.         if (is_null($connection)) {
  503.             $connection $this->getConnection();
  504.             if (PEAR::isError($connection)) {
  505.                 return $connection;
  506.             }
  507.         }
  508.         return @mysql_affected_rows($connection);
  509.     }
  510.  
  511.     // }}}
  512.     // {{{ _modifyQuery()
  513.  
  514.     /**
  515.      * Changes a query string for various DBMS specific reasons
  516.      *
  517.      * @param string $query  query to modify
  518.      * @return the new (modified) query
  519.      * @access protected
  520.      */
  521.     function _modifyQuery($query$is_manip$limit$offset)
  522.     {
  523.         if ($this->options['portability'MDB2_PORTABILITY_DELETE_COUNT{
  524.             // "DELETE FROM table" gives 0 affected rows in MySQL.
  525.             // This little hack lets you know how many rows were deleted.
  526.             if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i'$query)) {
  527.                 $query preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
  528.                                       'DELETE FROM \1 WHERE 1=1'$query);
  529.             }
  530.         }
  531.         if ($limit > 0
  532.             && !preg_match('/LIMIT\s*\d(\s*(,|OFFSET)\s*\d+)?/i'$query)
  533.         {
  534.             $query rtrim($query);
  535.             if (substr($query-1== ';'{
  536.                 $query substr($query0-1);
  537.             }
  538.             if ($is_manip{
  539.                 return $query . " LIMIT $limit";
  540.             else {
  541.                 return $query . " LIMIT $offset$limit";
  542.             }
  543.         }
  544.         return $query;
  545.     }
  546.  
  547.     // }}}
  548.     // {{{ getServerVersion()
  549.  
  550.     /**
  551.      * return version information about the server
  552.      *
  553.      * @param string     $native  determines if the raw version string should be returned
  554.      * @return mixed array with versoin information or row string
  555.      * @access public
  556.      */
  557.     function getServerVersion($native = false)
  558.     {
  559.         $connection $this->getConnection();
  560.         if (PEAR::isError($connection)) {
  561.             return $connection;
  562.         }
  563.         $server_info mysql_get_server_info($connection);
  564.         if (!$native{
  565.             $tmp explode('.'$server_info);
  566.             $tmp2 explode('-'@$tmp[2]);
  567.             $server_info = array(
  568.                 'major' => @$tmp[0],
  569.                 'minor' => @$tmp[1],
  570.                 'patch' => @$tmp2[0],
  571.                 'extra' => @$tmp2[1],
  572.                 'native' => $server_info,
  573.             );
  574.         }
  575.         return $server_info;
  576.     }
  577.  
  578.     // }}}
  579.     // {{{ replace()
  580.  
  581.     /**
  582.      * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
  583.      * query, except that if there is already a row in the table with the same
  584.      * key field values, the REPLACE query just updates its values instead of
  585.      * inserting a new row.
  586.      *
  587.      * The REPLACE type of query does not make part of the SQL standards. Since
  588.      * practically only MySQL implements it natively, this type of query is
  589.      * emulated through this method for other DBMS using standard types of
  590.      * queries inside a transaction to assure the atomicity of the operation.
  591.      *
  592.      * @access public
  593.      *
  594.      * @param string $table name of the table on which the REPLACE query will
  595.      *   be executed.
  596.      * @param array $fields associative array that describes the fields and the
  597.      *   values that will be inserted or updated in the specified table. The
  598.      *   indexes of the array are the names of all the fields of the table. The
  599.      *   values of the array are also associative arrays that describe the
  600.      *   values and other properties of the table fields.
  601.      *
  602.      *   Here follows a list of field properties that need to be specified:
  603.      *
  604.      *     value:
  605.      *           Value to be assigned to the specified field. This value may be
  606.      *           of specified in database independent type format as this
  607.      *           function can perform the necessary datatype conversions.
  608.      *
  609.      *     Default:
  610.      *           this property is required unless the Null property
  611.      *           is set to 1.
  612.      *
  613.      *     type
  614.      *           Name of the type of the field. Currently, all types Metabase
  615.      *           are supported except for clob and blob.
  616.      *
  617.      *     Default: no type conversion
  618.      *
  619.      *     null
  620.      *           Boolean property that indicates that the value for this field
  621.      *           should be set to null.
  622.      *
  623.      *           The default value for fields missing in INSERT queries may be
  624.      *           specified the definition of a table. Often, the default value
  625.      *           is already null, but since the REPLACE may be emulated using
  626.      *           an UPDATE query, make sure that all fields of the table are
  627.      *           listed in this function argument array.
  628.      *
  629.      *     Default: 0
  630.      *
  631.      *     key
  632.      *           Boolean property that indicates that this field should be
  633.      *           handled as a primary key or at least as part of the compound
  634.      *           unique index of the table that will determine the row that will
  635.      *           updated if it exists or inserted a new row otherwise.
  636.      *
  637.      *           This function will fail if no key field is specified or if the
  638.      *           value of a key field is set to null because fields that are
  639.      *           part of unique index they may not be null.
  640.      *
  641.      *     Default: 0
  642.      *
  643.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  644.      */
  645.     function replace($table$fields)
  646.     {
  647.         $count count($fields);
  648.         $query $values '';
  649.         $keys $colnum = 0;
  650.         for (reset($fields)$colnum $countnext($fields)$colnum++{
  651.             $name key($fields);
  652.             if ($colnum > 0{
  653.                 $query .= ',';
  654.                 $values.= ',';
  655.             }
  656.             $query.= $name;
  657.             if (isset($fields[$name]['null']&& $fields[$name]['null']{
  658.                 $value 'NULL';
  659.             else {
  660.                 $value $this->quote($fields[$name]['value']$fields[$name]['type']);
  661.             }
  662.             $values.= $value;
  663.             if (isset($fields[$name]['key']&& $fields[$name]['key']{
  664.                 if ($value === 'NULL'{
  665.                     return $this->raiseError(MDB2_ERROR_CANNOT_REPLACEnullnull,
  666.                         'replace: key value '.$name.' may not be NULL');
  667.                 }
  668.                 $keys++;
  669.             }
  670.         }
  671.         if ($keys == 0{
  672.             return $this->raiseError(MDB2_ERROR_CANNOT_REPLACEnullnull,
  673.                 'replace: not specified which fields are keys');
  674.         }
  675.  
  676.         $connection $this->getConnection();
  677.         if (PEAR::isError($connection)) {
  678.             return $connection;
  679.         }
  680.  
  681.         $query = "REPLACE INTO $table ($query) VALUES ($values)";
  682.         $this->last_query $query;
  683.         $this->debug($query'query');
  684.         $result $this->_doQuery($querytrue$connection);
  685.         if (PEAR::isError($result)) {
  686.             return $result;
  687.         }
  688.         return $this->_affectedRows($connection$result);
  689.     }
  690.  
  691.     // }}}
  692.     // {{{ nextID()
  693.  
  694.     /**
  695.      * returns the next free id of a sequence
  696.      *
  697.      * @param string $seq_name name of the sequence
  698.      * @param boolean $ondemand when true the seqence is
  699.      *                           automatic created, if it
  700.      *                           not exists
  701.      *
  702.      * @return mixed MDB2 Error Object or id
  703.      * @access public
  704.      */
  705.     function nextID($seq_name$ondemand = true)
  706.     {
  707.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  708.         $seqcol_name $this->quoteIdentifier($this->options['seqcol_name']true);
  709.         $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
  710.         $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  711.         $result $this->_doQuery($querytrue);
  712.         $this->popExpect();
  713.         if (PEAR::isError($result)) {
  714.             if ($ondemand && $result->getCode(== MDB2_ERROR_NOSUCHTABLE{
  715.                 $this->loadModule('Manager'nulltrue);
  716.                 // Since we are creating the sequence on demand
  717.                 // we know the first id = 1 so initialize the
  718.                 // sequence at 2
  719.                 $result $this->manager->createSequence($seq_name2);
  720.                 if (PEAR::isError($result)) {
  721.                     return $this->raiseError(MDB2_ERRORnullnull,
  722.                         'nextID: on demand sequence '.$seq_name.' could not be created');
  723.                 else {
  724.                     // First ID of a newly created sequence is 1
  725.                     return 1;
  726.                 }
  727.             }
  728.             return $result;
  729.         }
  730.         $value $this->lastInsertID();
  731.         if (is_numeric($value)) {
  732.             $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
  733.             $result $this->_doQuery($querytrue);
  734.             if (PEAR::isError($result)) {
  735.                 $this->warnings['nextID: could not delete previous sequence table values from '.$seq_name;
  736.             }
  737.         }
  738.         return $value;
  739.     }
  740.  
  741.     // }}}
  742.     // {{{ lastInsertID()
  743.  
  744.     /**
  745.      * returns the autoincrement ID if supported or $id
  746.      *
  747.      * @param mixed $id value as returned by getBeforeId()
  748.      * @param string $table name of the table into which a new row was inserted
  749.      * @return mixed MDB2 Error Object or id
  750.      * @access public
  751.      */
  752.     function lastInsertID($table = null$field = null)
  753.     {
  754.         $connection $this->getConnection();
  755.         if (PEAR::isError($connection)) {
  756.             return $connection;
  757.         }
  758.         $value @mysql_insert_id($connection);
  759.         if (!$value{
  760.             return $this->raiseError();
  761.         }
  762.         return $value;
  763.     }
  764.  
  765.     // }}}
  766.     // {{{ currID()
  767.  
  768.     /**
  769.      * returns the current id of a sequence
  770.      *
  771.      * @param string $seq_name name of the sequence
  772.      * @return mixed MDB2 Error Object or id
  773.      * @access public
  774.      */
  775.     function currID($seq_name)
  776.     {
  777.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  778.         $seqcol_name $this->quoteIdentifier($this->options['seqcol_name']true);
  779.         $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
  780.         return $this->queryOne($query'integer');
  781.     }
  782. }
  783.  
  784. class MDB2_Result_mysql extends MDB2_Result_Common
  785. {
  786.     // }}}
  787.     // {{{ fetchRow()
  788.  
  789.     /**
  790.      * Fetch a row and insert the data into an existing array.
  791.      *
  792.      * @param int       $fetchmode  how the array data should be indexed
  793.      * @param int    $rownum    number of the row where the data can be found
  794.      * @return int data array on success, a MDB2 error on failure
  795.      * @access public
  796.      */
  797.     function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT$rownum = null)
  798.     {
  799.         if (!is_null($rownum)) {
  800.             $seek $this->seek($rownum);
  801.             if (PEAR::isError($seek)) {
  802.                 return $seek;
  803.             }
  804.         }
  805.         if ($fetchmode == MDB2_FETCHMODE_DEFAULT{
  806.             $fetchmode $this->db->fetchmode;
  807.         }
  808.         if ($fetchmode MDB2_FETCHMODE_ASSOC{
  809.             $row @mysql_fetch_assoc($this->result);
  810.             if (is_array($row)
  811.                 && $this->db->options['portability'MDB2_PORTABILITY_FIX_CASE
  812.             {
  813.                 $row array_change_key_case($row$this->db->options['field_case']);
  814.             }
  815.         else {
  816.            $row @mysql_fetch_row($this->result);
  817.         }
  818.  
  819.         if (!$row{
  820.             if (is_null($this->result)) {
  821.                 $err =$this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  822.                     'fetchRow: resultset has already been freed');
  823.                 return $err;
  824.             }
  825.             $null = null;
  826.             return $null;
  827.         }
  828.         if ($this->db->options['portability'MDB2_PORTABILITY_EMPTY_TO_NULL{
  829.             $this->db->_fixResultArrayValues($rowMDB2_PORTABILITY_EMPTY_TO_NULL);
  830.         }
  831.         if (!empty($this->values)) {
  832.             $this->_assignBindColumns($row);
  833.         }
  834.         if (!empty($this->types)) {
  835.             $row $this->db->datatype->convertResultRow($this->types$row);
  836.         }
  837.         if ($fetchmode === MDB2_FETCHMODE_OBJECT{
  838.             $object_class $this->db->options['fetch_class'];
  839.             if ($object_class == 'stdClass'{
  840.                 $row = (object) $row;
  841.             else {
  842.                 $row &new $object_class($row);
  843.             }
  844.         }
  845.         ++$this->rownum;
  846.         return $row;
  847.     }
  848.  
  849.     // }}}
  850.     // {{{ _getColumnNames()
  851.  
  852.     /**
  853.      * Retrieve the names of columns returned by the DBMS in a query result.
  854.      *
  855.      * @return mixed                an associative array variable
  856.      *                               that will hold the names of columns. The
  857.      *                               indexes of the array are the column names
  858.      *                               mapped to lower case and the values are the
  859.      *                               respective numbers of the columns starting
  860.      *                               from 0. Some DBMS may not return any
  861.      *                               columns when the result set does not
  862.      *                               contain any rows.
  863.      *
  864.      *                               a MDB2 error on failure
  865.      * @access private
  866.      */
  867.     function _getColumnNames()
  868.     {
  869.         $columns = array();
  870.         $numcols $this->numCols();
  871.         if (PEAR::isError($numcols)) {
  872.             return $numcols;
  873.         }
  874.         for ($column = 0; $column $numcols$column++{
  875.             $column_name @mysql_field_name($this->result$column);
  876.             $columns[$column_name$column;
  877.         }
  878.         if ($this->db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  879.             $columns array_change_key_case($columns$this->db->options['field_case']);
  880.         }
  881.         return $columns;
  882.     }
  883.  
  884.     // }}}
  885.     // {{{ numCols()
  886.  
  887.     /**
  888.      * Count the number of columns returned by the DBMS in a query result.
  889.      *
  890.      * @return mixed integer value with the number of columns, a MDB2 error
  891.      *                        on failure
  892.      * @access public
  893.      */
  894.     function numCols()
  895.     {
  896.         $cols @mysql_num_fields($this->result);
  897.         if (is_null($cols)) {
  898.             if (is_null($this->result)) {
  899.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  900.                     'numCols: resultset has already been freed');
  901.             }
  902.             return $this->db->raiseError();
  903.         }
  904.         return $cols;
  905.     }
  906.  
  907.     // }}}
  908.     // {{{ free()
  909.  
  910.     /**
  911.      * Free the internal resources associated with result.
  912.      *
  913.      * @return boolean true on success, false if result is invalid
  914.      * @access public
  915.      */
  916.     function free()
  917.     {
  918.         $free @mysql_free_result($this->result);
  919.         if (!$free{
  920.             if (is_null($this->result)) {
  921.                 return MDB2_OK;
  922.             }
  923.             return $this->db->raiseError();
  924.         }
  925.         $this->result = null;
  926.         return MDB2_OK;
  927.     }
  928. }
  929.  
  930. {
  931.     // }}}
  932.     // {{{ seek()
  933.  
  934.     /**
  935.      * seek to a specific row in a result set
  936.      *
  937.      * @param int    $rownum    number of the row where the data can be found
  938.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  939.      * @access public
  940.      */
  941.     function seek($rownum = 0)
  942.     {
  943.         if ($this->rownum != ($rownum - 1&& !@mysql_data_seek($this->result$rownum)) {
  944.             if (is_null($this->result)) {
  945.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  946.                     'seek: resultset has already been freed');
  947.             }
  948.             return $this->db->raiseError(MDB2_ERROR_INVALIDnullnull,
  949.                 'seek: tried to seek to an invalid row number ('.$rownum.')');
  950.         }
  951.         $this->rownum $rownum - 1;
  952.         return MDB2_OK;
  953.     }
  954.  
  955.     // }}}
  956.     // {{{ valid()
  957.  
  958.     /**
  959.      * check if the end of the result set has been reached
  960.      *
  961.      * @return mixed true or false on sucess, a MDB2 error on failure
  962.      * @access public
  963.      */
  964.     function valid()
  965.     {
  966.         $numrows $this->numRows();
  967.         if (PEAR::isError($numrows)) {
  968.             return $numrows;
  969.         }
  970.         return $this->rownum ($numrows - 1);
  971.     }
  972.  
  973.     // }}}
  974.     // {{{ numRows()
  975.  
  976.     /**
  977.      * returns the number of rows in a result object
  978.      *
  979.      * @return mixed MDB2 Error Object or the number of rows
  980.      * @access public
  981.      */
  982.     function numRows()
  983.     {
  984.         $rows @mysql_num_rows($this->result);
  985.         if (is_null($rows)) {
  986.             if (is_null($this->result)) {
  987.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  988.                     'numRows: resultset has already been freed');
  989.             }
  990.             return $this->db->raiseError();
  991.         }
  992.         return $rows;
  993.     }
  994. }
  995.  
  996. class MDB2_Statement_mysql extends MDB2_Statement_Common
  997. {
  998.  
  999. }
  1000. ?>

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