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.87 2005/12/10 15:24:17 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)
  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.         $server_info $this->getServerVersion();
  400.         if (is_array($server_info)
  401.             && ($server_info['major'> 4)
  402.                 || ($server_info['major'> 4 && $server_info['minor'> 1)
  403.             )
  404.         {
  405.             $this->supported['sub_selects'= true;
  406.         }
  407.  
  408.         return MDB2_OK;
  409.     }
  410.  
  411.     // }}}
  412.     // {{{ disconnect()
  413.  
  414.     /**
  415.      * Log out and disconnect from the database.
  416.      *
  417.      * @return mixed true on success, false if not connected and error
  418.      *                 object on error
  419.      * @access public
  420.      */
  421.     function disconnect($force = true)
  422.     {
  423.         if (is_resource($this->connection)) {
  424.             if($this->in_transaction{
  425.                 $this->rollback();
  426.             }
  427.             if (!$this->opened_persistent || $force{
  428.                 @mysql_close($this->connection);
  429.             }
  430.             $this->connection = 0;
  431.             $this->in_transaction = false;
  432.         }
  433.         return MDB2_OK;
  434.     }
  435.  
  436.     // }}}
  437.     // {{{ _doQuery()
  438.  
  439.     /**
  440.      * Execute a query
  441.      * @param string $query  query
  442.      * @param boolean $is_manip  if the query is a manipulation query
  443.      * @param resource $connection 
  444.      * @param string $database_name 
  445.      * @return result or error object
  446.      * @access protected
  447.      */
  448.     function _doQuery($query$is_manip = false$connection = null$database_name = null)
  449.     {
  450.         $this->last_query $query;
  451.         $this->debug($query'query');
  452.         if ($this->options['disable_query']{
  453.             if ($is_manip{
  454.                 return 0;
  455.             }
  456.             return null;
  457.         }
  458.  
  459.         if (is_null($connection)) {
  460.             $connection $this->getConnection();
  461.             if (PEAR::isError($connection)) {
  462.                 return $connection;
  463.             }
  464.         }
  465.         if (is_null($database_name)) {
  466.             $database_name $this->database_name;
  467.         }
  468.  
  469.         if ($database_name{
  470.             if ($database_name != $this->connected_database_name{
  471.                 if (!@mysql_select_db($database_name$connection)) {
  472.                     return $this->raiseError();
  473.                 }
  474.                 $this->connected_database_name $database_name;
  475.             }
  476.         }
  477.  
  478.         $function $this->options['result_buffering']
  479.             ? 'mysql_query' 'mysql_unbuffered_query';
  480.         $result @$function($query$connection);
  481.         if (!$result{
  482.             return $this->raiseError();
  483.         }
  484.  
  485.         return $result;
  486.     }
  487.  
  488.     // }}}
  489.     // {{{ _affectedRows()
  490.  
  491.     /**
  492.      * returns the number of rows affected
  493.      *
  494.      * @param resource $result 
  495.      * @param resource $connection 
  496.      * @return mixed MDB2 Error Object or the number of rows affected
  497.      * @access private
  498.      */
  499.     function _affectedRows($connection$result = null)
  500.     {
  501.         if (is_null($connection)) {
  502.             $connection $this->getConnection();
  503.             if (PEAR::isError($connection)) {
  504.                 return $connection;
  505.             }
  506.         }
  507.         return @mysql_affected_rows($connection);
  508.     }
  509.  
  510.     // }}}
  511.     // {{{ _modifyQuery()
  512.  
  513.     /**
  514.      * Changes a query string for various DBMS specific reasons
  515.      *
  516.      * @param string $query  query to modify
  517.      * @return the new (modified) query
  518.      * @access protected
  519.      */
  520.     function _modifyQuery($query$is_manip$limit$offset)
  521.     {
  522.         if ($this->options['portability'MDB2_PORTABILITY_DELETE_COUNT{
  523.             // "DELETE FROM table" gives 0 affected rows in MySQL.
  524.             // This little hack lets you know how many rows were deleted.
  525.             if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i'$query)) {
  526.                 $query preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
  527.                                       'DELETE FROM \1 WHERE 1=1'$query);
  528.             }
  529.         }
  530.         if ($limit > 0
  531.             && !preg_match('/LIMIT\s*\d(\s*(,|OFFSET)\s*\d+)?/i'$query)
  532.         {
  533.             $query rtrim($query);
  534.             if (substr($query-1== ';'{
  535.                 $query substr($query0-1);
  536.             }
  537.             if ($is_manip{
  538.                 return $query . " LIMIT $limit";
  539.             else {
  540.                 return $query . " LIMIT $offset$limit";
  541.             }
  542.         }
  543.         return $query;
  544.     }
  545.  
  546.     // }}}
  547.     // {{{ getServerVersion()
  548.  
  549.     /**
  550.      * return version information about the server
  551.      *
  552.      * @param string     $native  determines if the raw version string should be returned
  553.      * @return mixed array with versoin information or row string
  554.      * @access public
  555.      */
  556.     function getServerVersion($native = false)
  557.     {
  558.         $connection $this->getConnection();
  559.         if (PEAR::isError($connection)) {
  560.             return $connection;
  561.         }
  562.         $server_info mysql_get_server_info($connection);
  563.         if (!$native{
  564.             $tmp explode('.'$server_info);
  565.             $tmp2 explode('-'@$tmp[2]);
  566.             $server_info = array(
  567.                 'major' => @$tmp[0],
  568.                 'minor' => @$tmp[1],
  569.                 'patch' => @$tmp2[0],
  570.                 'extra' => @$tmp2[1],
  571.                 'native' => $server_info,
  572.             );
  573.         }
  574.         return $server_info;
  575.     }
  576.  
  577.     // }}}
  578.     // {{{ replace()
  579.  
  580.     /**
  581.      * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
  582.      * query, except that if there is already a row in the table with the same
  583.      * key field values, the REPLACE query just updates its values instead of
  584.      * inserting a new row.
  585.      *
  586.      * The REPLACE type of query does not make part of the SQL standards. Since
  587.      * practically only MySQL implements it natively, this type of query is
  588.      * emulated through this method for other DBMS using standard types of
  589.      * queries inside a transaction to assure the atomicity of the operation.
  590.      *
  591.      * @access public
  592.      *
  593.      * @param string $table name of the table on which the REPLACE query will
  594.      *   be executed.
  595.      * @param array $fields associative array that describes the fields and the
  596.      *   values that will be inserted or updated in the specified table. The
  597.      *   indexes of the array are the names of all the fields of the table. The
  598.      *   values of the array are also associative arrays that describe the
  599.      *   values and other properties of the table fields.
  600.      *
  601.      *   Here follows a list of field properties that need to be specified:
  602.      *
  603.      *     value:
  604.      *           Value to be assigned to the specified field. This value may be
  605.      *           of specified in database independent type format as this
  606.      *           function can perform the necessary datatype conversions.
  607.      *
  608.      *     Default:
  609.      *           this property is required unless the Null property
  610.      *           is set to 1.
  611.      *
  612.      *     type
  613.      *           Name of the type of the field. Currently, all types Metabase
  614.      *           are supported except for clob and blob.
  615.      *
  616.      *     Default: no type conversion
  617.      *
  618.      *     null
  619.      *           Boolean property that indicates that the value for this field
  620.      *           should be set to null.
  621.      *
  622.      *           The default value for fields missing in INSERT queries may be
  623.      *           specified the definition of a table. Often, the default value
  624.      *           is already null, but since the REPLACE may be emulated using
  625.      *           an UPDATE query, make sure that all fields of the table are
  626.      *           listed in this function argument array.
  627.      *
  628.      *     Default: 0
  629.      *
  630.      *     key
  631.      *           Boolean property that indicates that this field should be
  632.      *           handled as a primary key or at least as part of the compound
  633.      *           unique index of the table that will determine the row that will
  634.      *           updated if it exists or inserted a new row otherwise.
  635.      *
  636.      *           This function will fail if no key field is specified or if the
  637.      *           value of a key field is set to null because fields that are
  638.      *           part of unique index they may not be null.
  639.      *
  640.      *     Default: 0
  641.      *
  642.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  643.      */
  644.     function replace($table$fields)
  645.     {
  646.         $count count($fields);
  647.         $query $values '';
  648.         $keys $colnum = 0;
  649.         for (reset($fields)$colnum $countnext($fields)$colnum++{
  650.             $name key($fields);
  651.             if ($colnum > 0{
  652.                 $query .= ',';
  653.                 $values.= ',';
  654.             }
  655.             $query.= $name;
  656.             if (isset($fields[$name]['null']&& $fields[$name]['null']{
  657.                 $value 'NULL';
  658.             else {
  659.                 $value $this->quote($fields[$name]['value']$fields[$name]['type']);
  660.             }
  661.             $values.= $value;
  662.             if (isset($fields[$name]['key']&& $fields[$name]['key']{
  663.                 if ($value === 'NULL'{
  664.                     return $this->raiseError(MDB2_ERROR_CANNOT_REPLACEnullnull,
  665.                         'replace: key value '.$name.' may not be NULL');
  666.                 }
  667.                 $keys++;
  668.             }
  669.         }
  670.         if ($keys == 0{
  671.             return $this->raiseError(MDB2_ERROR_CANNOT_REPLACEnullnull,
  672.                 'replace: not specified which fields are keys');
  673.         }
  674.  
  675.         $connection $this->getConnection();
  676.         if (PEAR::isError($connection)) {
  677.             return $connection;
  678.         }
  679.  
  680.         $query = "REPLACE INTO $table ($query) VALUES ($values)";
  681.         $this->last_query $query;
  682.         $this->debug($query'query');
  683.         $result $this->_doQuery($querytrue$connection);
  684.         if (PEAR::isError($result)) {
  685.             return $result;
  686.         }
  687.         return $this->_affectedRows($connection$result);
  688.     }
  689.  
  690.     // }}}
  691.     // {{{ nextID()
  692.  
  693.     /**
  694.      * returns the next free id of a sequence
  695.      *
  696.      * @param string $seq_name name of the sequence
  697.      * @param boolean $ondemand when true the seqence is
  698.      *                           automatic created, if it
  699.      *                           not exists
  700.      *
  701.      * @return mixed MDB2 Error Object or id
  702.      * @access public
  703.      */
  704.     function nextID($seq_name$ondemand = true)
  705.     {
  706.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  707.         $seqcol_name $this->quoteIdentifier($this->options['seqcol_name']true);
  708.         $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
  709.         $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  710.         $result $this->_doQuery($querytrue);
  711.         $this->popExpect();
  712.         if (PEAR::isError($result)) {
  713.             if ($ondemand && $result->getCode(== MDB2_ERROR_NOSUCHTABLE{
  714.                 $this->loadModule('Manager');
  715.                 // Since we are creating the sequence on demand
  716.                 // we know the first id = 1 so initialize the
  717.                 // sequence at 2
  718.                 $result $this->manager->createSequence($seq_name2);
  719.                 if (PEAR::isError($result)) {
  720.                     return $this->raiseError(MDB2_ERRORnullnull,
  721.                         'nextID: on demand sequence '.$seq_name.' could not be created');
  722.                 else {
  723.                     // First ID of a newly created sequence is 1
  724.                     return 1;
  725.                 }
  726.             }
  727.             return $result;
  728.         }
  729.         $value $this->lastInsertID();
  730.         if (is_numeric($value)) {
  731.             $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
  732.             $result $this->_doQuery($querytrue);
  733.             if (PEAR::isError($result)) {
  734.                 $this->warnings['nextID: could not delete previous sequence table values from '.$seq_name;
  735.             }
  736.         }
  737.         return $value;
  738.     }
  739.  
  740.     // }}}
  741.     // {{{ lastInsertID()
  742.  
  743.     /**
  744.      * returns the autoincrement ID if supported or $id
  745.      *
  746.      * @param mixed $id value as returned by getBeforeId()
  747.      * @param string $table name of the table into which a new row was inserted
  748.      * @return mixed MDB2 Error Object or id
  749.      * @access public
  750.      */
  751.     function lastInsertID($table = null$field = null)
  752.     {
  753.         $connection $this->getConnection();
  754.         if (PEAR::isError($connection)) {
  755.             return $connection;
  756.         }
  757.         $value @mysql_insert_id($connection);
  758.         if (!$value{
  759.             return $this->raiseError();
  760.         }
  761.         return $value;
  762.     }
  763.  
  764.     // }}}
  765.     // {{{ currID()
  766.  
  767.     /**
  768.      * returns the current id of a sequence
  769.      *
  770.      * @param string $seq_name name of the sequence
  771.      * @return mixed MDB2 Error Object or id
  772.      * @access public
  773.      */
  774.     function currID($seq_name)
  775.     {
  776.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  777.         $seqcol_name $this->quoteIdentifier($this->options['seqcol_name']true);
  778.         $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
  779.         return $this->queryOne($query'integer');
  780.     }
  781. }
  782.  
  783. class MDB2_Result_mysql extends MDB2_Result_Common
  784. {
  785.     // }}}
  786.     // {{{ fetchRow()
  787.  
  788.     /**
  789.      * Fetch a row and insert the data into an existing array.
  790.      *
  791.      * @param int       $fetchmode  how the array data should be indexed
  792.      * @param int    $rownum    number of the row where the data can be found
  793.      * @return int data array on success, a MDB2 error on failure
  794.      * @access public
  795.      */
  796.     function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT$rownum = null)
  797.     {
  798.         if (!is_null($rownum)) {
  799.             $seek $this->seek($rownum);
  800.             if (PEAR::isError($seek)) {
  801.                 return $seek;
  802.             }
  803.         }
  804.         if ($fetchmode == MDB2_FETCHMODE_DEFAULT{
  805.             $fetchmode $this->db->fetchmode;
  806.         }
  807.         if ($fetchmode MDB2_FETCHMODE_ASSOC{
  808.             $row @mysql_fetch_assoc($this->result);
  809.             if (is_array($row)
  810.                 && $this->db->options['portability'MDB2_PORTABILITY_FIX_CASE
  811.             {
  812.                 $row array_change_key_case($row$this->db->options['field_case']);
  813.             }
  814.         else {
  815.            $row @mysql_fetch_row($this->result);
  816.         }
  817.  
  818.         if (!$row{
  819.             if (is_null($this->result)) {
  820.                 $err =$this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  821.                     'fetchRow: resultset has already been freed');
  822.                 return $err;
  823.             }
  824.             $null = null;
  825.             return $null;
  826.         }
  827.         if ($this->db->options['portability'MDB2_PORTABILITY_EMPTY_TO_NULL{
  828.             $this->db->_fixResultArrayValues($rowMDB2_PORTABILITY_EMPTY_TO_NULL);
  829.         }
  830.         if (!empty($this->values)) {
  831.             $this->_assignBindColumns($row);
  832.         }
  833.         if (!empty($this->types)) {
  834.             $row $this->db->datatype->convertResultRow($this->types$row);
  835.         }
  836.         if ($fetchmode === MDB2_FETCHMODE_OBJECT{
  837.             $object_class $this->db->options['fetch_class'];
  838.             if ($object_class == 'stdClass'{
  839.                 $row = (object) $row;
  840.             else {
  841.                 $row &new $object_class($row);
  842.             }
  843.         }
  844.         ++$this->rownum;
  845.         return $row;
  846.     }
  847.  
  848.     // }}}
  849.     // {{{ _getColumnNames()
  850.  
  851.     /**
  852.      * Retrieve the names of columns returned by the DBMS in a query result.
  853.      *
  854.      * @return mixed                an associative array variable
  855.      *                               that will hold the names of columns. The
  856.      *                               indexes of the array are the column names
  857.      *                               mapped to lower case and the values are the
  858.      *                               respective numbers of the columns starting
  859.      *                               from 0. Some DBMS may not return any
  860.      *                               columns when the result set does not
  861.      *                               contain any rows.
  862.      *
  863.      *                               a MDB2 error on failure
  864.      * @access private
  865.      */
  866.     function _getColumnNames()
  867.     {
  868.         $columns = array();
  869.         $numcols $this->numCols();
  870.         if (PEAR::isError($numcols)) {
  871.             return $numcols;
  872.         }
  873.         for ($column = 0; $column $numcols$column++{
  874.             $column_name @mysql_field_name($this->result$column);
  875.             $columns[$column_name$column;
  876.         }
  877.         if ($this->db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  878.             $columns array_change_key_case($columns$this->db->options['field_case']);
  879.         }
  880.         return $columns;
  881.     }
  882.  
  883.     // }}}
  884.     // {{{ numCols()
  885.  
  886.     /**
  887.      * Count the number of columns returned by the DBMS in a query result.
  888.      *
  889.      * @return mixed integer value with the number of columns, a MDB2 error
  890.      *                        on failure
  891.      * @access public
  892.      */
  893.     function numCols()
  894.     {
  895.         $cols @mysql_num_fields($this->result);
  896.         if (is_null($cols)) {
  897.             if (is_null($this->result)) {
  898.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  899.                     'numCols: resultset has already been freed');
  900.             }
  901.             return $this->db->raiseError();
  902.         }
  903.         return $cols;
  904.     }
  905.  
  906.     // }}}
  907.     // {{{ free()
  908.  
  909.     /**
  910.      * Free the internal resources associated with result.
  911.      *
  912.      * @return boolean true on success, false if result is invalid
  913.      * @access public
  914.      */
  915.     function free()
  916.     {
  917.         $free @mysql_free_result($this->result);
  918.         if (!$free{
  919.             if (is_null($this->result)) {
  920.                 return MDB2_OK;
  921.             }
  922.             return $this->db->raiseError();
  923.         }
  924.         $this->result = null;
  925.         return MDB2_OK;
  926.     }
  927. }
  928.  
  929. {
  930.     // }}}
  931.     // {{{ seek()
  932.  
  933.     /**
  934.     * seek to a specific row in a result set
  935.     *
  936.     * @param int    $rownum    number of the row where the data can be found
  937.     * @return mixed MDB2_OK on success, a MDB2 error on failure
  938.     * @access public
  939.     */
  940.     function seek($rownum = 0)
  941.     {
  942.         if ($this->rownum != ($rownum - 1&& !@mysql_data_seek($this->result$rownum)) {
  943.             if (is_null($this->result)) {
  944.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  945.                     'seek: resultset has already been freed');
  946.             }
  947.             return $this->db->raiseError(MDB2_ERROR_INVALIDnullnull,
  948.                 'seek: tried to seek to an invalid row number ('.$rownum.')');
  949.         }
  950.         $this->rownum $rownum - 1;
  951.         return MDB2_OK;
  952.     }
  953.  
  954.     // }}}
  955.     // {{{ valid()
  956.  
  957.     /**
  958.     * check if the end of the result set has been reached
  959.     *
  960.     * @return mixed true or false on sucess, a MDB2 error on failure
  961.     * @access public
  962.     */
  963.     function valid()
  964.     {
  965.         $numrows $this->numRows();
  966.         if (PEAR::isError($numrows)) {
  967.             return $numrows;
  968.         }
  969.         return $this->rownum ($numrows - 1);
  970.     }
  971.  
  972.     // }}}
  973.     // {{{ numRows()
  974.  
  975.     /**
  976.     * returns the number of rows in a result object
  977.     *
  978.     * @return mixed MDB2 Error Object or the number of rows
  979.     * @access public
  980.     */
  981.     function numRows()
  982.     {
  983.         $rows @mysql_num_rows($this->result);
  984.         if (is_null($rows)) {
  985.             if (is_null($this->result)) {
  986.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  987.                     'numRows: resultset has already been freed');
  988.             }
  989.             return $this->raiseError();
  990.         }
  991.         return $rows;
  992.     }
  993. }
  994.  
  995. class MDB2_Statement_mysql extends MDB2_Statement_Common
  996. {
  997.  
  998. }
  999. ?>

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