Source for file mysql.php
Documentation is available at mysql.php
// vim: set et ts=4 sw=4 fdm=marker:
// +----------------------------------------------------------------------+
// +----------------------------------------------------------------------+
// | Copyright (c) 1998-2004 Manuel Lemos, Tomas V.V.Cox, |
// | Stig. S. Bakken, Lukas Smith |
// | All rights reserved. |
// +----------------------------------------------------------------------+
// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
// | API as well as database abstraction for PHP applications. |
// | This LICENSE is in the BSD license style. |
// | Redistribution and use in source and binary forms, with or without |
// | modification, are permitted provided that the following conditions |
// | Redistributions of source code must retain the above copyright |
// | notice, this list of conditions and the following disclaimer. |
// | Redistributions in binary form must reproduce the above copyright |
// | notice, this list of conditions and the following disclaimer in the |
// | documentation and/or other materials provided with the distribution. |
// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
// | Lukas Smith nor the names of his contributors may be used to endorse |
// | or promote products derived from this software without specific prior|
// | written permission. |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
// | POSSIBILITY OF SUCH DAMAGE. |
// +----------------------------------------------------------------------+
// | Author: Lukas Smith <smith@backendmedia.com> |
// +----------------------------------------------------------------------+
// $Id: mysql.php,v 1.13 2004/04/25 10:04:59 lsmith Exp $
* @author Lukas Smith <smith@backendmedia.com>
$this->phptype = 'mysql';
$this->dbsyntax = 'mysql';
$this->supported['summary_functions'] = true;
$this->options['default_table_type'] = false;
* This method is used to collect information about an error
if (isset ($ecode_map[$native_code])) {
$error = $ecode_map[$native_code];
return array ($error, $native_code, $native_msg);
* Quotes a string so it can be safely used in a query. It will quote
* the text so it can safely be used within a query.
* @param string $text the input string to quote
* @return string quoted string
* Quote a string so it can be safely used as a table or column name
* Quoting style depends on which database driver is being used.
* MySQL can't handle the backtick character (<kbd>`</kbd>) in
* @param string $str identifier name to be quoted
* @return string quoted identifier string
* Define whether database changes done on the database be automatically
* committed. This function may also implicitly start or end a transaction.
* @param boolean $auto_commit flag that indicates whether the database
* changes should be committed right after
* executing every query statement. If this
* argument is 0 a transaction implicitly
* started. Otherwise, if a transaction is
* in progress it is ended by committing any
* database changes that were pending.
* @return mixed MDB2_OK on success, a MDB2 error on failure
$this->debug(($auto_commit ? 'On' : 'Off'), 'autoCommit');
if (!isset ($this->supported['transactions'])) {
'autoCommit: transactions are not in use');
$result = $this->query('COMMIT');
$result = $this->query('SET AUTOCOMMIT = 1');
$result = $this->query('SET AUTOCOMMIT = 0');
$this->in_transaction = !$auto_commit;
* Commit the database changes done during a transaction that is in
* progress. This function may only be called when auto-committing is
* disabled, otherwise it will fail. Therefore, a new transaction is
* implicitly started after committing the pending changes.
* @return mixed MDB2_OK on success, a MDB2 error on failure
$this->debug('commit transaction', 'commit');
if (!isset ($this->supported['transactions'])) {
'commit: transactions are not in use');
'commit: transaction changes are being auto commited');
return $this->query('COMMIT');
* Cancel any database changes done during a transaction that is in
* progress. This function may only be called when auto-committing is
* disabled, otherwise it will fail. Therefore, a new transaction is
* implicitly started after canceling the pending changes.
* @return mixed MDB2_OK on success, a MDB2 error on failure
$this->debug('rolling back transaction', 'rollback');
if (!isset ($this->supported['transactions'])) {
'rollback: transactions are not in use');
'rollback: transactions can not be rolled back when changes are auto commited');
return $this->query('ROLLBACK');
* Connect to the database
* @return true on success, MDB2 Error Object on failure
if ($this->connection != 0 ) {
&& $this->opened_persistent == $this->options['persistent']
if (!PEAR ::loadExtension ($this->phptype)) {
'connect: extension '. $this->phptype. ' is not compiled into PHP');
$function = ($this->options['persistent'] ? 'mysql_pconnect' : 'mysql_connect');
if (isset ($dsninfo['protocol']) && $dsninfo['protocol'] == 'unix') {
$dbhost = ':' . $dsninfo['socket'];
$dbhost = $dsninfo['hostspec'] ? $dsninfo['hostspec'] : 'localhost';
if (!empty ($dsninfo['port'])) {
$dbhost .= ':' . $dsninfo['port'];
$user = $dsninfo['username'];
$pw = $dsninfo['password'];
$connection = @$function($dbhost, $user, $pw, true );
$this->connection = $connection;
$this->connected_dsn = $this->dsn;
$this->connected_database_name = '';
$this->opened_persistent = $this->options['persistent'];
if ($this->options['use_transactions']) {
$this->options['default_table_type'] = 'BDB';
$this->options['default_table_type'] = '';
$default_table_type = $this->options['default_table_type'];
if ($default_table_type) {
$this->options['default_table_type'] = 'BDB';
if (isset ($this->supported['transactions'])) {
$this->warnings[] = $default_table_type.
' is not a transaction-safe default table type';
$this->warnings[] = $default_table_type.
' is not a supported default table type';
if (!@mysql_query('SET AUTOCOMMIT = 0', $this->connection)) {
$this->in_transaction = true;
* all the RDBMS specific things needed close a DB connection
if ($this->connection != 0 ) {
unset ($GLOBALS['_MDB2_databases'][$this->db_index]);
* This method is used by backends to alter queries for various
* @param string $query query to modify
* @return the new (modified) query
function _modifyQuery ($query)
// "DELETE FROM table" gives 0 affected rows in mysql.
// This little hack lets you know how many rows were deleted.
if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
'/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
'DELETE FROM \1 WHERE 1=1', $query
* Send a query to the database and return any results
* @param string $query the SQL query
* @param mixed $types string or array that contains the types of the
* columns in the result set
* @param mixed $result_class string which specifies which result class to use
* @param mixed $result_wrap_class string which specifies which class to wrap results in
* @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
function &query($query, $types = null , $result_class = false , $result_wrap_class = false )
$offset = $this->row_offset;
$limit = $this->row_limit;
$this->row_offset = $this->row_limit = 0;
$query .= " LIMIT $limit";
$query .= " LIMIT $offset,$limit";
$query = $this->_modifyQuery ($query);
$this->debug($query, 'query');
&& $this->database_name != $this->connected_database_name
$this->connected_database_name = $this->database_name;
$function = $this->options['result_buffering']
? 'mysql_query' : 'mysql_unbuffered_query';
if ($result = @$function($query, $this->connection)) {
$result_class = $this->options['result_buffering']
? $this->options['buffered_result_class'] : $this->options['result_class'];
$class_name = sprintf($result_class, $this->phptype);
$result = & new $class_name($this, $result);
$err = $result->setResultTypes ($types);
if (!$result_wrap_class) {
$result_wrap_class = $this->options['result_wrap_class'];
if ($result_wrap_class) {
$result = & new $result_wrap_class($result);
* returns the affected rows of a query
* @return mixed MDB2 Error Object or number of rows
if ($affected_rows === false ) {
* simple subselect emulation for Mysql
* @param string $query the SQL query for the subselect that may only
* @param string $type determines type of the field
* @return string comma seperated values
if ($this->supported['sub_selects'] == true ) {
return $this->datatype->implodeArray ($col, $type);
* Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
* query, except that if there is already a row in the table with the same
* key field values, the REPLACE query just updates its values instead of
* The REPLACE type of query does not make part of the SQL standards. Since
* practically only MySQL implements it natively, this type of query is
* emulated through this method for other DBMS using standard types of
* queries inside a transaction to assure the atomicity of the operation.
* @param string $table name of the table on which the REPLACE query will
* @param array $fields associative array that describes the fields and the
* values that will be inserted or updated in the specified table. The
* indexes of the array are the names of all the fields of the table. The
* values of the array are also associative arrays that describe the
* values and other properties of the table fields.
* Here follows a list of field properties that need to be specified:
* Value to be assigned to the specified field. This value may be
* of specified in database independent type format as this
* function can perform the necessary datatype conversions.
* this property is required unless the Null property
* Name of the type of the field. Currently, all types Metabase
* are supported except for clob and blob.
* Default: no type conversion
* Boolean property that indicates that the value for this field
* The default value for fields missing in INSERT queries may be
* specified the definition of a table. Often, the default value
* is already null, but since the REPLACE may be emulated using
* an UPDATE query, make sure that all fields of the table are
* listed in this function argument array.
* Boolean property that indicates that this field should be
* handled as a primary key or at least as part of the compound
* unique index of the table that will determine the row that will
* updated if it exists or inserted a new row otherwise.
* This function will fail if no key field is specified or if the
* value of a key field is set to null because fields that are
* part of unique index they may not be null.
* @return mixed MDB2_OK on success, a MDB2 error on failure
for ($keys = 0 , $query = $values = '',reset($fields), $colnum = 0;
next($fields), $colnum++ )
if (isset ($fields[$name]['null']) && $fields[$name]['null']) {
$value = $this->quote($fields[$name]['value'], $fields[$name]['type']);
if (isset ($fields[$name]['key']) && $fields[$name]['key']) {
'replace: key value '. $name. ' may not be NULL');
'replace: not specified which fields are keys');
return $this->query(" REPLACE INTO $table ($query) VALUES ($values)" );
* returns the next free id of a sequence
* @param string $seq_name name of the sequence
* @param boolean $ondemand when true the seqence is
* automatic created, if it
* @return mixed MDB2 Error Object or id
function nextID($seq_name, $ondemand = true )
$result = & $this->query(" INSERT INTO $sequence_name VALUES (NULL)" );
// Since we are creating the sequence on demand
// we know the first id = 1 so initialize the
$result = $this->manager->createSequence ($seq_name, 2 );
'nextID: on demand sequence '. $seq_name. ' could not be created');
// First ID of a newly created sequence is 1
$value = $this->queryOne('SELECT LAST_INSERT_ID()', 'integer');
$this->warnings[] = 'nextID: could not delete previous sequence table values from '. $seq_name;
* returns the current id of a sequence
* @param string $seq_name name of the sequence
* @return mixed MDB2 Error Object or id
return $this->queryOne("SELECT MAX(". $this->options['seqname_col_name']." ) FROM $sequence_name" , 'integer');
class MDB2_Result_mysql extends MDB2_Result_Common
function MDB2_Result_mysql (&$mdb, &$result)
parent ::MDB2_Result_Common ($mdb, $result);
* fetch value from a result set
* @param int $rownum number of the row where the data can be found
* @param int $colnum field number where the data can be found
* @return mixed string on success, a MDB2 error on failure
function fetch ($rownum = 0 , $colnum = 0 )
'fetch: resultset has already been freed');
if (isset ($this->types[$colnum])) {
$value = $this->mdb->datatype ->convertResult ($value, $this->types[$colnum]);
* Fetch a row and insert the data into an existing array.
* @param int $fetchmode how the array data should be indexed
* @return int data array on success, a MDB2 error on failure
function fetchRow ($fetchmode = MDB2_FETCHMODE_DEFAULT )
$fetchmode = $this->mdb->fetchmode;
'fetchRow: resultset has already been freed');
if (isset ($this->types)) {
$row = $this->mdb->datatype ->convertResultRow ($this->types, $row);
$this->mdb->_convertEmptyArrayValuesToNull ($row);
* Retrieve the names of columns returned by the DBMS in a query result.
* @return mixed an associative array variable
* that will hold the names of columns. The
* indexes of the array are the column names
* mapped to lower case and the values are the
* respective numbers of the columns starting
* from 0. Some DBMS may not return any
* columns when the result set does not
* a MDB2 error on failure
function getColumnNames ()
$numcols = $this->numCols ();
for ($column = 0; $column < $numcols; $column++ ) {
$columns[$column_name] = $column;
* Count the number of columns returned by the DBMS in a query result.
* @return mixed integer value with the number of columns, a MDB2 error
'numCols: resultset has already been freed');
return $this->mdb->raiseError ();
* Free the internal resources associated with result.
* @return boolean true on success, false if result is invalid
return $this->mdb->raiseError ();
class MDB2_BufferedResult_mysql extends MDB2_Result_mysql
function MDB2_BufferedResult_mysql (&$mdb, &$result)
parent ::MDB2_Result_mysql ($mdb, $result);
* seek to a specific row in a result set
* @param int $rownum number of the row where the data can be found
* @return mixed MDB2_OK on success, a MDB2 error on failure
function seek ($rownum = 0 )
'seek: resultset has already been freed');
'seek: tried to seek to an invalid row number ('. $rownum. ')');
$this->rownum = $rownum - 1;
* check if the end of the result set has been reached
* @return mixed true or false on sucess, a MDB2 error on failure
$numrows = $this->numRows ();
return $this->rownum < ($numrows - 1 );
* returns the number of rows in a result object
* @return mixed MDB2 Error Object or the number of rows
'numRows: resultset has already been freed');
return $this->raiseError ();
Documentation generated on Mon, 11 Mar 2019 10:15:51 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.
|