Source for file mysql.php
Documentation is available at mysql.php
/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
// +----------------------------------------------------------------------+
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2004 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Author: Stig Bakken <ssb@php.net> |
// | Maintainer: Daniel Convissor <danielc@php.net> |
// +----------------------------------------------------------------------+
// $Id: mysql.php,v 1.71 2004/04/07 04:56:58 danielc Exp $
// XXX ERRORMSG: The error message from the mysql function should
require_once 'DB/common.php';
* Database independent query interface definition for PHP's MySQL
* This is for MySQL versions 4.0 and below.
* @version $Id: mysql.php,v 1.71 2004/04/07 04:56:58 danielc Exp $
* @author Stig Bakken <ssb@php.net>
var $fetchmode = DB_FETCHMODE_ORDERED; /* Default fetch mode */
* Connect to a database and log in as the specified user.
* @param $dsn the data source name (see DB::parseDSN for syntax)
* @param $persistent (optional) whether the connection should
* @return int DB_OK on success, a DB error on failure
function connect($dsninfo, $persistent = false )
if ($dsninfo['protocol'] && $dsninfo['protocol'] == 'unix') {
$dbhost = ':' . $dsninfo['socket'];
$dbhost = $dsninfo['hostspec'] ? $dsninfo['hostspec'] : 'localhost';
$dbhost .= ':' . $dsninfo['port'];
$connect_function = $persistent ? 'mysql_pconnect' : 'mysql_connect';
if ($dbhost && $dsninfo['username'] && isset ($dsninfo['password'])) {
$conn = @$connect_function($dbhost, $dsninfo['username'],
} elseif ($dbhost && $dsninfo['username']) {
$conn = @$connect_function($dbhost, $dsninfo['username']);
$conn = @$connect_function($dbhost);
} elseif (empty ($php_errormsg)) {
if ($dsninfo['database']) {
// fix to allow calls to different databases in the same script
$this->_db = $dsninfo['database'];
* Log out and disconnect from the database.
* @return bool true on success, false if not connected.
* Send a query to MySQL and return the results as a MySQL resource
* @return mixed returns a valid MySQL result for successful SELECT
* queries, DB_OK for other successful queries. A DB error is
$numrows = $this->numrows ($result);
$this->num_rows[(int) $result] = $numrows;
* Move the internal mysql result pointer to the next available result
* This method has not been implemented yet.
* @param a valid sql result resource
* Fetch a row and insert the data into an existing array.
* Formating of the array and the data therein are configurable.
* See DB_result::fetchInto() for more information.
* @param resource $result query result identifier
* @param array $arr (reference) array where data from the row
* @param int $fetchmode how the resulting array should be indexed
* @param int $rownum the row number to fetch
* @return mixed DB_OK on success, null when end of result set is
* @see DB_result::fetchInto()
function fetchInto ($result, &$arr, $fetchmode, $rownum=null )
// See: http://bugs.php.net/bug.php?id=22328
// for why we can't check errors on fetching
$errno = @mysql_errno($this->connection);
return $this->mysqlRaiseError($errno);
* Even though this DBMS already trims output, we do this because
* a field might have intentional whitespace at the end that
* gets removed by DB_PORTABILITY_RTRIM under another driver.
$this->_rtrimArrayValues ($arr);
$this->_convertNullArrayValuesToEmpty ($arr);
* Free the internal resources associated with $result.
* @param $result MySQL result identifier
* @return bool true on success, false if $result is invalid
* Get the number of columns in a result set.
* @param $result MySQL result identifier
* @return int the number of columns per row in $result
* Get the number of rows in a result set.
* @param $result MySQL result identifier
* @return int the number of rows in $result
* Enable/disable automatic commits
// XXX if $this->transaction_opcount > 0, we should probably
* Commit the current transaction.
* Roll back (undo) the current transaction.
* Gets the number of rows affected by the data manipulation
* query. For other queries, this function returns 0.
* @return number of rows affected by the last query
* Get the native error code of the last error (if any) that
* occured on the current connection.
* @return int native MySQL error code
* Returns the next free id in a sequence
* @param string $seq_name name of the sequence
* @param boolean $ondemand when true, the seqence is automatically
* created if it does not exist
* @return int the next id number in the sequence. DB_Error if problem.
* @see DB_common::nextID()
function nextId($seq_name, $ondemand = true )
$seqname = $this->getSequenceName ($seq_name);
$this->pushErrorHandling (PEAR_ERROR_RETURN );
$result = $this->query(" UPDATE ${seqname} ".
'SET id=LAST_INSERT_ID(id+1)');
$this->popErrorHandling ();
// Sequence table must be empty for some reason, so fill it and return 1
// Obtain a user-level lock
$result = $this->getOne(" SELECT GET_LOCK('${seqname}_lock',10)" );
// Failed to get the lock, bail with a DB_ERROR_NOT_LOCKED error
$result = $this->query(" REPLACE INTO ${seqname} VALUES (0)" );
$result = $this->getOne(" SELECT RELEASE_LOCK('${seqname}_lock')" );
// We know what the result will be, so no need to try again
/** ONDEMAND TABLE CREATION **/
} elseif ($ondemand && DB::isError($result) &&
// see _BCsequence() comment
$result = $this->_BCsequence ($seqname);
* @param string $seq_name name of the new sequence
* @return int DB_OK on success. A DB_Error object is returned if
* @see DB_common::createSequence()
$seqname = $this->getSequenceName ($seq_name);
$res = $this->query(" CREATE TABLE ${seqname} ".
'(id INTEGER UNSIGNED AUTO_INCREMENT NOT NULL,'.
// insert yields value 1, nextId call will generate ID 2
$res = $this->query(" INSERT INTO ${seqname} VALUES(0)" );
return $this->query(" UPDATE ${seqname} SET id = 0;" );
* @param string $seq_name name of the sequence to be deleted
* @return int DB_OK on success. DB_Error if problems.
* @see DB_common::dropSequence()
return $this->query('DROP TABLE ' . $this->getSequenceName ($seq_name));
* Backwards compatibility with old sequence emulation implementation
* @param string $seqname The sequence name to clean up
* @return mixed DB_Error or true
function _BCsequence ($seqname)
// Obtain a user-level lock... this will release any previous
// application locks, but unlike LOCK TABLES, it does not abort
// the current transaction and is much less frequently used.
$result = $this->getOne(" SELECT GET_LOCK('${seqname}_lock',10)" );
// Failed to get the lock, can't do the conversion, bail
// with a DB_ERROR_NOT_LOCKED error
$highest_id = $this->getOne(" SELECT MAX(id) FROM ${seqname}" );
// This should kill all rows except the highest
// We should probably do something if $highest_id isn't
// numeric, but I'm at a loss as how to handle that...
$result = $this->query(" DELETE FROM ${seqname} WHERE id <> $highest_id" );
// If another thread has been waiting for this lock,
// it will go thru the above procedure, but will have no
$result = $this->getOne(" SELECT RELEASE_LOCK('${seqname}_lock')" );
* 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
* @deprecated Deprecated in release 1.6.0
* Escape a string according to the current DBMS's standards
* @param string $str the string to be escaped
* @return string the escaped string
// "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)) {
'DELETE FROM \1 WHERE 1=1', $query);
// {{{ modifyLimitQuery()
return $query . " LIMIT $count";
return $query . " LIMIT $from, $count";
* Gather information about an error, then use that info to create a
* DB error object and finally return that object.
* @param integer $errno PEAR error number (usually a DB constant) if
* manually raising an error
* @return object DB error object
* @see DB_common::errorCode()
* @see DB_common::raiseError()
// Doing this in case mode changes during runtime.
return $this->raiseError($errno, null , null , null ,
* Returns information about a table or a result set.
* @param object|string $result DB_result object from a query or a
* string containing the name of a table
* @param int $mode a valid tableInfo mode
* @return array an associative array with the information requested
* or an error object if something is wrong
* @see DB_common::tableInfo()
if (isset ($result->result )) {
* Probably received a result object.
* Extract the result resource identifier.
* Probably received a table name.
* Create a result resource identifier.
* Probably received a result resource identifier.
* Deprecated. Here for compatibility only.
$case_func = 'strtolower';
// made this IF due to performance (one if is faster than $count if's)
for ($i=0; $i< $count; $i++ ) {
$res['num_fields']= $count;
for ($i=0; $i< $count; $i++ ) {
$res['order'][$res[$i]['name']] = $i;
$res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
// free the result only if we were called on a table
* Returns the query needed to get some backend info
* @param string $type What kind of info you want to retrieve
* @return string The SQL query string
$sql = 'select distinct User from user';
if ($this->dsn['database'] != 'mysql') {
$dsn['database'] = 'mysql';
$sql = $db->getCol ($sql);
// XXX Fixme the mysql driver should take care of this
Documentation generated on Mon, 11 Mar 2019 10:14:53 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.
|