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

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