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

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