Source for file Base.php
Documentation is available at Base.php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
* DB_Table_Base Base class for DB_Table and DB_Table_Database
* This utility class contains properties and methods that are common
* to DB_Table and DB_Table database. These are all related to one of:
* - DB/MDB2 connection object [ $db and $backend properties ]
* - Error handling [ throwError() method, $error and $_primary_subclass ]
* - SELECT queries [ select*() methods, $sql & $fetchmode* properties]
* - buildSQL() and quote() SQL utilities
* @author David C. Morse <morse@php.net>
* @license http://www.gnu.org/copyleft/lesser.html LGPL
* @version $Id: Base.php,v 1.3 2007/06/14 05:10:46 morse Exp $
* Base class for DB_Table and DB_Table_Database
* @author David C. Morse <morse@php.net>
* The PEAR DB/MDB2 object that connects to the database.
* The backend type, which must be 'db' or 'mdb2'
* If there is an error on instantiation, this captures that error.
* This property is used only for errors encountered in the constructor
* at instantiation time. To check if there was an instantiation error...
* $obj =& new DB_Table_*();
* // ... error handling code here ...
* Baseline SELECT maps for buildSQL() and select*() methods.
* Format of rows in sets returned by the select() method
* This should be one of the DB/MDB2_FETCHMODE_* constant values, such as
* MDB2_FETCHMODE_ASSOC, MDB2_FETCHMODE_ORDERED, or MDB2_FETCHMODE_OBJECT.
* It determines whether select() returns represents individual rows as
* associative arrays with column name keys, ordered/sequential arrays,
* or objects with column names mapped to properties. Use corresponding
* DB_FETCHMODE_* constants for use with the DB backend. It has no effect
* upon the return value of selectResult().
* If a 'fetchmode' element is set for a specific query array, the query
* fetchmode will override this DB_Table or DB_Table_Database property.
* If no value is set for the query or the DB_Table_Base object, the value
* or default set in the underlying DB/MDB2 object will be used.
* Class of objects to use for rows returned as objects by select()
* When fetchmode is DB/MDB2_FETCHMODE_OBJECT, use this class for each
* returned row in rsults of select(). May be overridden by value of
* 'fetchmode_object_class'. If no class name is set in the query or
* the DB_Table_Base, defaults to that set in the DB/MDB2 object, or
* to default of StdObject.
* Upper case name of primary subclass, 'DB_TABLE' or 'DB_TABLE_DATABASE'
* This should be set in the constructor of the child class, and is
* used in the DB_Table_Base::throwError() method to determine the
* location of the relevant error codes and messages. Error codes and
* error code messages are defined in class $this->_primary_subclass.
* Messages are stored in $GLOBALS['_' . $this->_primary_subclass]['error']
var $_primary_subclass = null;
* Specialized version of throwError() modeled on PEAR_Error.
* Throws a PEAR_Error with an error message based on an error code
* and corresponding error message defined in $this->_primary_subclass
* @param string $code An error code constant
* @param string $extra Extra text for the error (in addition to the
* regular error message).
* @return object PEAR_Error
// get the error message text based on the error code
$index = '_' . $this->_primary_subclass;
$text = $this->_primary_subclass . " Error - \n"
. $GLOBALS[$index]['error'][$code];
// add any additional error text
$error = PEAR ::throwError ($text, $code);
* Overwrites one or more error messages, e.g., to internationalize them.
* May be used to change messages stored in global array $GLOBALS[$class_key]
* @param mixed $code If string, the error message with code $code will be
* overwritten by $message. If array, each key is a code
* and each value is a new message.
* @param string $message Only used if $key is not an array.
$index = '_' . $this->_primary_subclass;
foreach ($code as $single_code => $single_message) {
$GLOBALS[$index]['error'][$single_code] = $single_message;
$GLOBALS[$index]['error'][$code] = $message;
* Returns SQL SELECT string constructed from sql query array
* @param mixed $query SELECT query array, or key string of $this->sql
* @param string $filter SQL snippet to AND with default WHERE clause
* @param string $order SQL snippet to override default ORDER BY clause
* @param int $start The row number from which to start result set
* @param int $count The number of rows to list in the result set.
* @return string SQL SELECT command string (or PEAR_Error on failure)
function buildSQL($query, $filter = null , $order = null ,
$start = null , $count = null )
// Is $query a query array or a key of $this->sql ?
if (isset ($this->sql[$query])) {
$query = $this->sql[$query];
constant($this->_primary_subclass . '_ERR_SQL_UNDEF'),
constant($this->_primary_subclass . '_ERR_SQL_NOT_STRING'));
// Construct SQL command from parts
if (isset ($query['select'])) {
$s[] = 'SELECT ' . $query['select'];
if (isset ($query['from'])) {
$s[] = 'FROM ' . $query['from'];
} elseif ($this->_primary_subclass == 'DB_TABLE') {
$s[] = 'FROM ' . $this->table;
if (isset ($query['join'])) {
if (isset ($query['where'])) {
$s[] = 'WHERE ( ' . $query['where'] . ' )';
$s[] = ' AND ( '. $filter . ' )';
$s[] = 'WHERE ' . $query['where'];
$s[] = 'WHERE ' . $filter;
if (isset ($query['group'])) {
$s[] = 'GROUP BY ' . $query['group'];
if (isset ($query['having'])) {
$s[] = 'HAVING '. $query['having'];
// If $order parameter is set, override 'order' element
$s[] = 'ORDER BY '. $order;
} elseif (isset ($query['order'])) {
$s[] = 'ORDER BY ' . $query['order'];
// add LIMIT if requested
$db->setLimit ($count, $start);
$cmd = $db->modifyLimitQuery (
* Selects rows using one of the DB/MDB2 get*() methods.
* @param string $query SQL SELECT query array, or a key of the
* $this->sql property array.
* @param string $filter SQL snippet to AND with default WHERE clause
* @param string $order SQL snippet to override default ORDER BY clause
* @param int $start The row number from which to start result set
* @param int $count The number of rows to list in the result set.
* @param array $params Parameters for placeholder substitutions, if any
* @return mixed An array of records from the table if anything but
* ('getOne'), a single value (if 'getOne'), or a PEAR_Error
* @see DB_Table_Base::_swapModes()
function select($query, $filter = null , $order = null ,
$start = null , $count = null , $params = array ())
// Is $query a query array or a key of $this->sql ?
// On output from this block, $query is an array
if (isset ($this->sql[$query])) {
$query = $this->sql[$query];
constant($this->_primary_subclass . '_ERR_SQL_UNDEF'),
constant($this->_primary_subclass . '_ERR_SQL_NOT_STRING'));
// build the base command
$sql = $this->buildSQL($query, $filter, $order, $start, $count);
if (PEAR ::isError ($sql)) {
// set the get*() method name
if (isset ($query['get'])) {
// DB_Table assumes you are using a shared PEAR DB/MDB2 object.
// Record fetchmode settings, to be restored before returning.
$restore_mode = $db->fetchmode;
$restore_class = $db->getOption ('fetch_class');
$restore_class = $db->fetchmode_object_class;
if (isset ($query['fetchmode'])) {
$fetchmode = $query['fetchmode'];
if (isset ($query['fetchmode_object_class'])) {
$fetchmode_object_class = $query['fetchmode_object_class'];
$this->_swapModes ($fetchmode, $fetchmode_object_class);
// make sure params is an array
$params = (array) $params;
$result = $db->extended ->$method($sql, null , $params);
$result = $db->$method($sql, 0 , $params);
$result = $db->$method($sql, false , $params);
$result = $db->$method($sql, $params);
// restore old fetch_mode and fetch_object_class back
$this->_swapModes ($restore_mode, $restore_class);
* Selects rows as a DB_Result/MDB2_Result_* object.
* @param string $query The name of the SQL SELECT to use from the
* $this->sql property array.
* @param string $filter SQL snippet to AND to the default WHERE clause
* @param string $order SQL snippet to override default ORDER BY clause
* @param int $start The record number from which to start result set
* @param int $count The number of records to list in result set.
* @param array $params Parameters for placeholder substitutions, if any.
* @return object DB_Result/MDB2_Result_* object on success
* (PEAR_Error on failure)
* @see DB_Table::_swapModes()
function selectResult($query, $filter = null , $order = null ,
$start = null , $count = null , $params = array ())
// Is $query a query array or a key of $this->sql ?
// On output from this block, $query is an array
if (isset ($this->sql[$query])) {
$query = $this->sql[$query];
constant($this->_primary_subclass . '_ERR_SQL_UNDEF'),
constant($this->_primary_subclass . '_ERR_SQL_NOT_STRING'));
// build the base command
$sql = $this->buildSQL($query, $filter, $order, $start, $count);
if (PEAR ::isError ($sql)) {
// DB_Table assumes you are using a shared PEAR DB/MDB2 object.
// Record fetchmode settings, to be restored afterwards.
$restore_mode = $db->fetchmode;
$restore_class = $db->getOption ('fetch_class');
$restore_class = $db->fetchmode_object_class;
if (isset ($query['fetchmode'])) {
$fetchmode = $query['fetchmode'];
if (isset ($query['fetchmode_object_class'])) {
$fetchmode_object_class = $query['fetchmode_object_class'];
$this->_swapModes ($fetchmode, $fetchmode_object_class);
// make sure params is an array
$params = (array) $params;
$stmt = & $db->prepare ($sql);
if (PEAR ::isError ($stmt)) {
$result = & $stmt->execute ($params);
$result = & $db->query ($sql, $params);
$this->_swapModes ($restore_mode, $restore_class);
* Counts the number of rows which will be returned by a query.
* This function works identically to {@link select()}, but it
* returns the number of rows returned by a query instead of the
* query results themselves.
* @author Ian Eure <ian@php.net>
* @param string $query The name of the SQL SELECT to use from the
* $this->sql property array.
* @param string $filter Ad-hoc SQL snippet to AND with the default
* @param string $order Ad-hoc SQL snippet to override the default
* SELECT ORDER BY clause.
* @param int $start Row number from which to start listing in result
* @param int $count Number of rows to list in result set
* @param array $params Parameters to use in placeholder substitutions
* @return int Number of records from the table (or PEAR_Error on failure)
* @see DB_Table::select()
function selectCount($query, $filter = null , $order = null ,
$start = null , $count = null , $params = array ())
// Is $query a query array or a key of $this->sql ?
if (isset ($this->sql[$query])) {
$count_query = $this->sql[$query];
constant($this->_primary_subclass . '_ERR_SQL_UNDEF'),
constant($this->_primary_subclass . '_ERR_SQL_NOT_STRING'));
// Use Table name as default 'from' if child class is DB_TABLE
if ($this->_primary_subclass == 'DB_TABLE') {
if (!isset ($query['from'])) {
$count_query['from'] = $this->table;
// If the query is a stored query in $this->sql, then create a corresponding
// key for the count query, or check if the count-query already exists
// Create an sql key name for this count-query
$count_key = '__count_' . $sql_key;
// Check if a this count query alread exists in $this->sql
if (isset ($this->sql[$count_key])) {
// If a count-query does not already exist, create $count_query array
$count_query = $this->sql[$count_key];
// Is a count-field set for the query?
if (!isset ($count_query['count']) ||
trim($count_query['count']) == '') {
$count_query['count'] = '*';
// Replace the SELECT fields with a COUNT() command
$count_query['select'] = " COUNT({$count_query['count']})";
// Replace the 'get' key so we only get one result item
$count_query['get'] = 'one';
// Create a new count-query in $this->sql
$this->sql[$count_key] = $count_query;
// Retrieve the count results
return $this->select($count_query, $filter, $order,
$start, $count, $params);
* Changes the $this->db PEAR DB/MDB2 object fetchmode and
* fetchmode_object_class.
* @param string $new_mode A DB/MDB2_FETCHMODE_* constant. If null,
* defaults to whatever the DB/MDB2 object is currently using.
* @param string $new_class The object class to use for results when
* the $db object is in DB/MDB2_FETCHMODE_OBJECT fetch mode. If null,
* defaults to whatever the the DB/MDB2 object is currently using.
function _swapModes ($new_mode, $new_class)
// get the old (current) mode and class
$old_mode = $db->fetchmode;
$old_class = $db->getOption ('fetch_class');
$old_class = $db->fetchmode_object_class;
// don't need to swap anything if the new modes are both
// null or if the old and new modes already match.
($old_mode == $new_mode && $old_class == $new_class)) {
// set the default new mode
// set the default new class
$db->setFetchMode ($new_mode, $new_class);
* Returns SQL condition equating columns to literal values.
* The parameter $data is an associative array in which keys are
* column names and values are corresponding values. The method
* returns an SQL string that is true if the value of every
* specified database columns is equal to the corresponding
* $data = array( 'c1' => 'thing', 'c2' => 23, 'c3' => 0.32 )
* then buildFilter($data) returns a string
* c1 => 'thing' AND c2 => 23 AND c3 = 0.32
* in which string values are replaced by SQL literal values,
* quoted and escaped as necessary.
* Values are quoted and escaped as appropriate for each data
* type and the backend RDBMS, using the MDB2::quote() or
* DB::smartQuote() method. The behavior depends on the PHP type
* of the value: string values are quoted and escaped, while
* integer and float numerical values are not. Boolean values
* in $data are represented as 0 or 1, consistent with the way
* booleans are stored by DB_Table.
* Null values: The treatment of null values in $data depends upon
* the value of the $match parameter . If $match == 'simple', an
* empty string is returned if any $value of $data with a key in
* $data_key is null. If $match == 'partial', the returned SQL
* expression equates only the relevant non-null values of $data
* to the values of corresponding database columns. If
* $match == 'full', the function returns an empty string if all
* of the relevant values of data are null, and returns a
* PEAR_Error if some of the selected values are null and others
* @param array $data associative array, keys are column names
* @return string SQL expression equating values in $data to
* values of columns named by keys.
// Check $match type value
if (!in_array($match, array ('simple', 'partial', 'full'))) {
foreach ($data as $key => $value) {
if ($match == 'full' && isset ($found_null)) {
$value = $value ? '1' : '0';
$value = $this->db->quote ($value);
$value = $this->db->quoteSmart ($value);
$filter[] = " $key = $value";
if ($match == 'simple') {
return ''; // if any value in $data is null
} elseif ($match == 'full') {
* c-hanging-comment-ender-p: nil
Documentation generated on Mon, 11 Mar 2019 15:06:20 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.
|