Class DB_common

Description

DB_common is a base class for DB implementations, and must be inherited by all such

  • author: Stig Bakken <ssb@php.net>
  • author: Tomas V.V.Cox <cox@idecnet.com>
  • version: $Id: common.php,v 1.103 2004/06/24 15:24:56 danielc Exp $

Located in /maintenance/libraries/pear/DB/common.php (line 35)

PEAR
   |
   --DB_common
Direct descendents
Class Description
 class DB_dbase Database independent query interface definition for PHP's dbase extension.
 class DB_msql Database independent query interface definition for PHP's Mini-SQL extension.
 class DB_mysqli Database independent query interface definition for PHP's mysqli extension.
 class DB_mssql Database independent query interface definition for PHP's Microsoft SQL Server extension.
 class DB_sqlite Database independent query interface definition for the SQLite PECL extension.
 class DB_oci8 Database independent query interface definition for PHP's Oracle 8 call-interface extension.
 class DB_ibase Database independent query interface definition for PHP's Interbase extension.
 class DB_mysql Database independent query interface definition for PHP's MySQL extension.
 class DB_ifx Database independent query interface definition for PHP's Informix extension.
 class DB_sybase Database independent query interface definition for PHP's Sybase extension.
 class DB_pgsql Database independent query interface definition for PHP's PostgreSQL extension.
 class DB_odbc Database independent query interface definition for PHP's ODBC extension.
 class DB_fbsql Database independent query interface definition for PHP's FrontBase extension.
Variable Summary
Method Summary
 DB_common DB_common ()
 mixed affectedRows ()
 mixed autoCommit ([boolean $onoff = false])
 mixed autoExecute (string $table, array $fields_values, [int $mode = DB_AUTOQUERY_INSERT], [string $where = false])
 resource autoPrepare (string $table, array $table_fields, [int $mode = DB_AUTOQUERY_INSERT], [string $where = false])
 string buildManipSQL (string $table, array $table_fields, int $mode, [string $where = false])
 mixed commit ()
 int createSequence (string $seq_name)
 int dropSequence (string $seq_name)
 int errorCode (mixed $nativecode)
 string errorMessage (integer $dbcode)
 mixed errorNative ()
 string escapeSimple (string $str)
 object a &execute (resource $stmt, [mixed $data = array()])
 mixed executeEmulateQuery (resource $stmt, [mixed $data = array()])
 mixed executeMultiple (resource $stmt, array $data)
 void freePrepared ($stmt $stmt)
 array &getAll (string $query, [array $params = array()], [int $fetchmode = DB_FETCHMODE_DEFAULT])
 array &getAssoc (string $query, [boolean $force_array = false], [mixed $params = array()], [int $fetchmode = DB_FETCHMODE_DEFAULT], [boolean $group = false])
 array &getCol (string $query, mixed $col, [mixed $params = array()])
 mixed getListOf (string $type)
 mixed &getOne (string $query, [mixed $params = array()])
 mixed getOption (string $option)
 array &getRow (string $query, [array $params = array()], [int $fetchmode = DB_FETCHMODE_DEFAULT])
 string getSequenceName (string $sqn)
 string getSpecialQuery (string $type)
 void getTables ()
 mixed &limitQuery (string $query, integer $from, integer $count, [mixed $params = array()])
 the modifyLimitQuery (string $query, integer $from, integer $count, [mixed $params = array()])
 the modifyQuery (string $query)
 int nextId (string $seq_name, [boolean $ondemand = true])
 mixed numRows (object DB_Result $result)
 mixed prepare (string $query)
 bool provides (array $feature)
 mixed &query (string $query, [mixed $params = array()])
 string quote ([string $string = null])
 string quoteIdentifier (string $str)
 mixed quoteSmart (mixed $in)
 string quoteString (mixed $string)
 object a &raiseError ([mixed $code = DB_ERROR], [int $mode = null], [mixed $options = null], [string $userinfo = null], [mixed $nativecode = null])
 mixed rollback ()
 void setFetchMode (integer $fetchmode, [string $object_class = 'stdClass'])
 int setOption (string $option, mixed $value)
 array tableInfo (object|string $result, [int $mode = null])
 string toString ()
 void _convertNullArrayValuesToEmpty (array &$array)
 void _rtrimArrayValues (array &$array)
Variables
resource $dbh (line 118)

DB handle

array $errorcode_map = array() (line 52)

assoc mapping native error codes to DB ones

array $features = array() (line 46)

assoc of capabilities for this DB implementation

$features['limit'] => 'emulate' => emulate with fetch row by number 'alter' => alter the query false => skip rows

integer $fetchmode = DB_FETCHMODE_ORDERED (line 88)

Redefined in descendants as:
string $fetchmode_object_class = 'stdClass' (line 93)
string $last_query = '' (line 83)
array $options = array(
'persistent' => false,
'ssl' => false,
'debug' => 0,
'seqname_format' => '%s_seq',
'autofree' => false,
'portability' => DB_PORTABILITY_NONE,
'optimize' => 'performance', // Deprecated. Use 'portability'.
)
(line 104)

Run-time configuration options.

The 'optimize' option has been deprecated. Use the 'portability' option instead.

string $prepared_queries (line 73)
integer $prepare_maxstmt = 0 (line 78)
Methods
Constructor DB_common (line 149)

Constructor

DB_common DB_common ()
affectedRows (line 1696)

Returns the affected rows of a query

  • return: DB_Error or number of rows
  • access: public
mixed affectedRows ()

Redefined in descendants as:
autoCommit (line 1634)

enable automatic Commit

  • return: DB_Error
  • access: public
mixed autoCommit ([boolean $onoff = false])
  • boolean $onoff

Redefined in descendants as:
autoExecute (line 847)

Automaticaly generate an insert or update query and call prepare() and execute() with it

mixed autoExecute (string $table, array $fields_values, [int $mode = DB_AUTOQUERY_INSERT], [string $where = false])
  • string $table: name of the table
  • array $fields_values: assoc ($key=>$value) where $key is a field name and $value its value
  • int $mode: type of query to make (DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE)
  • string $where: in case of update queries, this string will be put after the sql WHERE statement
autoPrepare (line 826)

Automaticaly generate an insert or update query and pass it to prepare()

resource autoPrepare (string $table, array $table_fields, [int $mode = DB_AUTOQUERY_INSERT], [string $where = false])
  • string $table: name of the table
  • array $table_fields: ordered array containing the fields names
  • int $mode: type of query to make (DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE)
  • string $where: in case of update queries, this string will be put after the sql WHERE statement
buildManipSQL (line 875)

Make automaticaly an sql query for prepare()

Example : buildManipSQL('table_sql', array('field1', 'field2', 'field3'), DB_AUTOQUERY_INSERT) will return the string : INSERT INTO table_sql (field1,field2,field3) VALUES (?,?,?) NB : - This belongs more to a SQL Builder class, but this is a simple facility

  • Be carefull ! If you don't give a $where param with an UPDATE query, all the records of the table will be updated !

  • return: sql query for prepare()
  • access: public
string buildManipSQL (string $table, array $table_fields, int $mode, [string $where = false])
  • string $table: name of the table
  • array $table_fields: ordered array containing the fields names
  • int $mode: type of query to make (DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE)
  • string $where: in case of update queries, this string will be put after the sql WHERE statement
commit (line 1649)

starts a Commit

  • return: DB_Error
  • access: public
mixed commit ()

Redefined in descendants as:
createSequence (line 1782)

Creates a new sequence

The name of a given sequence is determined by passing the string provided in the $seq_name argument through PHP's sprintf() function using the value from the seqname_format option as the sprintf()'s format argument.

seqname_format is set via setOption().

int createSequence (string $seq_name)
  • string $seq_name: name of the new sequence

Redefined in descendants as:
dropSequence (line 1801)

Deletes a sequence

int dropSequence (string $seq_name)
  • string $seq_name: name of the sequence to be deleted

Redefined in descendants as:
errorCode (line 416)

Map native error codes to DB's portable ones

Requires that the DB implementation's constructor fills in the $errorcode_map property.

  • return: a portable DB error code, or DB_ERROR if this DB implementation has no mapping for the given error code.
  • access: public
int errorCode (mixed $nativecode)
  • mixed $nativecode: the native error code, as returned by the backend database extension (string or integer)

Redefined in descendants as:
errorMessage (line 439)

Map a DB error code to a textual message. This is actually just a wrapper for DB::errorMessage()

  • return: the corresponding error message, of false if the error code was unknown
  • access: public
string errorMessage (integer $dbcode)
  • integer $dbcode: the DB error code
errorNative (line 1711)

Returns an errormessage, provides by the database

  • return: DB_Error or message
  • access: public
mixed errorNative ()

Redefined in descendants as:
  • DB_mysqli::errorNative() : Get the native error code of the last error (if any) that occured on the current connection.
  • DB_mssql::errorNative() : Determine MS SQL Server error code by querying @@ERROR.
  • DB_sqlite::errorNative() : Get the native error string of the last error (if any) that occured on the current connection.
  • DB_oci8::errorNative() : Get the native error code of the last error (if any) that occured on the current connection. This does not work, as OCIError does not work unless given a statement. If OCIError does return something, so will this.
  • DB_mysql::errorNative() : Get the native error code of the last error (if any) that occured on the current connection.
  • DB_ifx::errorNative() : Get the native error message of the last error (if any) that occured on the current connection.
  • DB_sybase::errorNative() : Get the last server error messge (if any)
  • DB_pgsql::errorNative() : Get the native error code of the last error (if any) that occured on the current connection.
  • DB_odbc::errorNative() : Get the native error code of the last error (if any) that occured on the current connection.
  • DB_fbsql::errorNative() : Get the native error code of the last error (if any) that occured on the current connection.
escapeSimple (line 379)

Escape a string according to the current DBMS's standards

In SQLite, this makes things safe for inserts/updates, but may cause problems when performing text comparisons against columns containing binary data. See the PHP manual for more info.

string escapeSimple (string $str)
  • string $str: the string to be escaped

Redefined in descendants as:
execute (line 947)

Executes a DB statement prepared with prepare()

Example 1.

  1. <?php
  2. $sth = $dbh->prepare('INSERT INTO tbl (a, b, c) VALUES (?, !, &)');
  3. $data = array(
  4. "John's text",
  5. "'it''s good'",
  6. 'filename.txt'
  7. );
  8. $res =& $dbh->execute($sth, $data);
  9. ?>

  • return:

    new DB_Result or a DB_Error when fail

    ibase and oci8 have their own execute() methods.

  • access: public
  • see: DB_common::prepare()
object a &execute (resource $stmt, [mixed $data = array()])
  • resource $stmt: a DB statement resource returned from prepare()
  • mixed $data: array, string or numeric data to be used in execution of the statement. Quantity of items passed must match quantity of placeholders in query: meaning 1 placeholder for non-array parameters or 1 placeholder per array element.

Redefined in descendants as:
executeEmulateQuery (line 982)

Emulates the execute statement, when not supported

  • return: a string containing the real query run when emulating prepare/execute. A DB error code is returned on failure.
  • access: private
  • see: DB_common::execute()
mixed executeEmulateQuery (resource $stmt, [mixed $data = array()])
  • resource $stmt: a DB statement resource returned from execute()
  • mixed $data: array, string or numeric data to be used in execution of the statement. Quantity of items passed must match quantity of placeholders in query: meaning 1 placeholder for non-array parameters or 1 placeholder per array element.
executeMultiple (line 1039)

This function does several execute() calls on the same statement handle

$data must be an array indexed numerically from 0, one execute call is done for every "row" in the array.

If an error occurs during execute(), executeMultiple() does not execute the unfinished rows, but rather returns that error.

mixed executeMultiple (resource $stmt, array $data)
  • resource $stmt: query handle from prepare()
  • array $data: numeric array containing the data to insert into the query
freePrepared (line 1059)

Free the resource used in a prepared query

void freePrepared ($stmt $stmt)
  • $stmt $stmt: The resurce returned by the prepare() function

Redefined in descendants as:
getAll (line 1565)

Fetch all the rows returned from a query

  • return: an nested array. DB error on failure.
  • access: public
array &getAll (string $query, [array $params = array()], [int $fetchmode = DB_FETCHMODE_DEFAULT])
  • string $query: the SQL query
  • array $params: array to be used in execution of the statement. Quantity of array elements must match quantity of placeholders in query. This function does NOT support scalars.
  • int $fetchmode: the fetch mode to use
getAssoc (line 1458)

Fetch the entire result set of a query and return it as an associative array using the first column as the key

If the result set contains more than two columns, the value will be an array of the values from column 2-n. If the result set contains only two columns, the returned value will be a scalar with the value of the second column (unless forced to an array with the $force_array parameter). A DB error code is returned on errors. If the result set contains fewer than two columns, a DB_ERROR_TRUNCATED error is returned.

For example, if the table "mytable" contains:

  ID      TEXT       DATE
 --------------------------------
  1       'one'      944679408
  2       'two'      944679408
  3       'three'    944679408

Then the call getAssoc('SELECT id,text FROM mytable') returns:

   array(
     '1' => 'one',
     '2' => 'two',
     '3' => 'three',
   )

...while the call getAssoc('SELECT id,text,date FROM mytable') returns:

   array(
     '1' => array('one', '944679408'),
     '2' => array('two', '944679408'),
     '3' => array('three', '944679408')
   )

If the more than one row occurs with the same value in the first column, the last row overwrites all previous ones by default. Use the $group parameter if you don't want to overwrite like this. Example:

 getAssoc('SELECT category,id,name FROM mytable', false, null,
          DB_FETCHMODE_ASSOC, true) returns:

   array(
     '1' => array(array('id' => '4', 'name' => 'number four'),
                  array('id' => '6', 'name' => 'number six')
            ),
     '9' => array(array('id' => '4', 'name' => 'number four'),
                  array('id' => '6', 'name' => 'number six')
            )
   )

Keep in mind that database functions in PHP usually return string values for results regardless of the database's internal type.

  • return: associative array with results from the query. DB Error on failure.
  • access: public
array &getAssoc (string $query, [boolean $force_array = false], [mixed $params = array()], [int $fetchmode = DB_FETCHMODE_DEFAULT], [boolean $group = false])
  • string $query: the SQL query
  • boolean $force_array: used only when the query returns exactly two columns. If true, the values of the returned array will be one-element arrays instead of scalars.
  • mixed $params: array, string or numeric data to be used in execution of the statement. Quantity of items passed must match quantity of placeholders in query: meaning 1 placeholder for non-array parameters or 1 placeholder per array element.
  • int $fetchmode: the fetch mode to use
  • boolean $group: if true, the values of the returned array is wrapped in another array. If the same key value (in the first column) repeats itself, the values will be appended to this array instead of overwriting the existing values.
getCol (line 1326)

Fetch a single column from a result set and return it as an indexed array

  • return: an indexed array with the data from the first row at index 0, or a DB error code
  • access: public
  • see: DB_common::query()
array &getCol (string $query, mixed $col, [mixed $params = array()])
  • string $query: the SQL query
  • mixed $col: which column to return (integer [column number, starting at 0] or string [column name])
  • mixed $params: array, string or numeric data to be used in execution of the statement. Quantity of items passed must match quantity of placeholders in query: meaning 1 placeholder for non-array parameters or 1 placeholder per array element.
getListOf (line 1964)

list internal DB info valid values for $type are db dependent, often: databases, users, view, functions

  • return: DB_Error or the requested data
  • access: public
mixed getListOf (string $type)
  • string $type: type of requested info
getOne (line 1209)

Fetch the first column of the first row of data returned from a query

Takes care of doing the query and freeing the results when finished.

  • return: the returned value of the query. DB_Error on failure.
  • access: public
mixed &getOne (string $query, [mixed $params = array()])
  • string $query: the SQL query
  • mixed $params: array, string or numeric data to be used in execution of the statement. Quantity of items passed must match quantity of placeholders in query: meaning 1 placeholder for non-array parameters or 1 placeholder per array element.
getOption (line 724)

Returns the value of an option

  • return: the option value
mixed getOption (string $option)
  • string $option: option name
getRow (line 1257)

Fetch the first row of data returned from a query

Takes care of doing the query and freeing the results when finished.

  • return: the first row of results as an array indexed from 0, or a DB error code.
  • access: public
array &getRow (string $query, [array $params = array()], [int $fetchmode = DB_FETCHMODE_DEFAULT])
  • string $query: the SQL query
  • array $params: array to be used in execution of the statement. Quantity of array elements must match quantity of placeholders in query. This function does NOT support scalars.
  • int $fetchmode: the fetch mode to use
getSequenceName (line 1733)

Generate the name used inside the database for a sequence

The createSequence() docblock contains notes about storing sequence names.

string getSequenceName (string $sqn)
  • string $sqn: the sequence's public name
getSpecialQuery (line 1989)

Returns the query needed to get some backend info

  • return: The SQL query string
  • access: public
string getSpecialQuery (string $type)
  • string $type: What kind of info you want to retrieve

Redefined in descendants as:
getTables (line 1945)
  • deprecated: Deprecated in release 1.2 or lower
void getTables ()
limitQuery (line 1175)

Generates a limited query

  • return: a DB_Result object, DB_OK or a DB_Error
  • access: public
mixed &limitQuery (string $query, integer $from, integer $count, [mixed $params = array()])
  • string $query: query
  • integer $from: the row to start to fetching
  • integer $count: the numbers of rows to fetch
  • mixed $params: array, string or numeric data to be used in execution of the statement. Quantity of items passed must match quantity of placeholders in query: meaning 1 placeholder for non-array parameters or 1 placeholder per array element.
modifyLimitQuery (line 1106)

This method is used by backends to alter limited queries

  • return: new (modified) query
  • access: private
the modifyLimitQuery (string $query, integer $from, integer $count, [mixed $params = array()])
  • string $query: query to modify
  • integer $from: the row to start to fetching
  • integer $count: the numbers of rows to fetch

Redefined in descendants as:
modifyQuery (line 1088)

This method is used by backends to alter queries for various reasons

It is defined here to assure that all implementations have this method defined.

  • return: new (modified) query
  • access: private
the modifyQuery (string $query)
  • string $query: query to modify

Redefined in descendants as:
nextId (line 1755)

Returns the next free id in a sequence

int nextId (string $seq_name, [boolean $ondemand = true])
  • string $seq_name: name of the sequence
  • boolean $ondemand: when true, the seqence is automatically created if it does not exist

Redefined in descendants as:
numRows (line 1681)

Returns the number of rows in a result object

  • return: DB_Error or the number of rows
  • access: public
mixed numRows (object DB_Result $result)
  • object DB_Result $result: the result object to check

Redefined in descendants as:
prepare (line 778)

Prepares a query for multiple execution with execute()

Creates a query that can be run multiple times. Each time it is run, the placeholders, if any, will be replaced by the contents of execute()'s $data argument.

Three types of placeholders can be used:

  • ? scalar value (i.e. strings, integers). The system will automatically quote and escape the data.
  • ! value is inserted 'as is'
  • & requires a file name. The file's contents get inserted into the query (i.e. saving binary data in a db)
Example 1.
  1. <?php
  2. $sth = $dbh->prepare('INSERT INTO tbl (a, b, c) VALUES (?, !, &)');
  3. $data = array(
  4. "John's text",
  5. "'it''s good'",
  6. 'filename.txt'
  7. );
  8. $res = $dbh->execute($sth, $data);
  9. ?>

Use backslashes to escape placeholder characters if you don't want them to be interpreted as placeholders:

    "UPDATE foo SET col=? WHERE col='over \& under'"

With some database backends, this is emulated.

ibase and oci8 have their own prepare() methods.

  • return: DB statement resource on success. DB_Error on failure.
  • access: public
  • see: DB_common::execute()
mixed prepare (string $query)
  • string $query: query to be prepared

Redefined in descendants as:
provides (line 394)

Tell whether a DB implementation or its backend extension supports a given feature

  • return: whether this DB implementation supports $feature
  • access: public
bool provides (array $feature)
  • array $feature: name of the feature (see the DB class doc)
query (line 1135)

Send a query to the database and return any results with a DB_result object

The query string can be either a normal statement to be sent directly to the server OR if $params are passed the query can have placeholders and it will be passed through prepare() and execute().

mixed &query (string $query, [mixed $params = array()])
  • string $query: the SQL query or the statement to prepare
  • mixed $params: array, string or numeric data to be used in execution of the statement. Quantity of items passed must match quantity of placeholders in query: meaning 1 placeholder for non-array parameters or 1 placeholder per array element.

Redefined in descendants as:
quote (line 191)

DEPRECATED: Quotes a string so it can be safely used in a query

string quote ([string $string = null])
  • string $string: the input string to quote

Redefined in descendants as:
quoteIdentifier (line 236)

Quote a string so it can be safely used as a table or column name

Delimiting style depends on which database driver is being used.

NOTE: just because you CAN use delimited identifiers doesn't mean you SHOULD use them. In general, they end up causing way more problems than they solve.

Portability is broken by using the following characters inside delimited identifiers:

  • backtick (`) -- due to MySQL
  • double quote (") -- due to Oracle
  • brackets ([ or ]) -- due to Access
Delimited identifiers are known to generally work correctly under the following drivers:
  • mssql
  • mysql
  • mysqli
  • oci8
  • odbc(access)
  • odbc(db2)
  • pgsql
  • sqlite
  • sybase
InterBase doesn't seem to be able to use delimited identifiers via PHP 4. They work fine under PHP 5.

  • return: quoted identifier string
  • access: public
  • since: 1.6.0
string quoteIdentifier (string $str)
  • string $str: identifier name to be quoted

Redefined in descendants as:
quoteSmart (line 347)

Format input so it can be safely used in a query

The output depends on the PHP data type of input and the database type being used.

  • return:

    the format of the results depends on the input's PHP type:

    • input -> returns
    • null -> the string NULL
    • integer or double -> the unquoted number
    • &type.bool; -> output depends on the driver in use Most drivers return integers: 1 if true or 0 if false. Some return strings: TRUE if true or FALSE if false. Finally one returns strings: T if true or F if false. Here is a list of each DBMS, the values returned and the suggested column type:
      • dbase -> T/F (Logical)
      • fbase -> TRUE/FALSE (BOOLEAN)
      • ibase -> 1/0 (SMALLINT) [1]
      • ifx -> 1/0 (SMALLINT) [1]
      • msql -> 1/0 (INTEGER)
      • mssql -> 1/0 (BIT)
      • mysql -> 1/0 (TINYINT(1))
      • mysqli -> 1/0 (TINYINT(1))
      • oci8 -> 1/0 (NUMBER(1))
      • odbc -> 1/0 (SMALLINT) [1]
      • pgsql -> TRUE/FALSE (BOOLEAN)
      • sqlite -> 1/0 (INTEGER)
      • sybase -> 1/0 (TINYINT(1))
      [1] Accommodate the lowest common denominator because not all versions of have BOOLEAN.
    • other (including strings and numeric strings) -> the data with single quotes escaped by preceeding single quotes, backslashes are escaped by preceeding backslashes, then the whole string is encapsulated between single quotes

  • access: public
  • see: DB_common::escapeSimple()
  • since: 1.6.0
mixed quoteSmart (mixed $in)
  • mixed $in: data to be quoted

Redefined in descendants as:
quoteString (line 167)

DEPRECATED: Quotes a string so it can be safely used within string delimiters in a query

string quoteString (mixed $string)
raiseError (line 476)

Communicate an error and invoke error callbacks, etc

Basically a wrapper for PEAR::raiseError without the message string.

  • return: PEAR error object
  • see: PEAR_Error
  • access: public
object a &raiseError ([mixed $code = DB_ERROR], [int $mode = null], [mixed $options = null], [string $userinfo = null], [mixed $nativecode = null])
  • mixed $code: integer error code, or a PEAR error object (all other parameters are ignored if this parameter is an object
  • int $mode: error mode, see PEAR_Error docs
  • mixed $options: If error mode is PEAR_ERROR_TRIGGER, this is the error level (E_USER_NOTICE etc). If error mode is PEAR_ERROR_CALLBACK, this is the callback function, either as a function name, or as an array of an object and method name. For other error modes this parameter is ignored.
  • string $userinfo: Extra debug information. Defaults to the last query and native error code.
  • mixed $nativecode: Native error code, integer or string depending the backend.
rollback (line 1664)

starts a rollback

  • return: DB_Error
  • access: public
mixed rollback ()

Redefined in descendants as:
setFetchMode (line 530)

Sets which fetch mode should be used by default on queries on this connection

void setFetchMode (integer $fetchmode, [string $object_class = 'stdClass'])
  • integer $fetchmode: DB_FETCHMODE_ORDERED or DB_FETCHMODE_ASSOC, possibly bit-wise OR'ed with DB_FETCHMODE_FLIPPED.
  • string $object_class: The class of the object to be returned by the fetch methods when the DB_FETCHMODE_OBJECT mode is selected. If no class is specified by default a cast to object from the assoc array row will be done. There is also the posibility to use and extend the 'DB_row' class.
setOption (line 679)

Set run-time configuration options for PEAR DB

Options, their data types, default values and description:

  • autofree boolean = false
    should results be freed automatically when there are no more rows?
  • debug integer = 0
    debug level
  • persistent boolean = false
    should the connection be persistent?
  • portability integer = DB_PORTABILITY_NONE
    portability mode constant (see below)
  • seqname_format string = %s_seq
    the sprintf() format string used on sequence names. This format is applied to sequence names passed to createSequence(), nextID() and dropSequence().
  • ssl boolean = false
    use ssl to connect?

-----------------------------------------

PORTABILITY MODES

These modes are bitwised, so they can be combined using | and removed using ^. See the examples section below on how to do this.

DB_PORTABILITY_NONE turn off all portability features

This mode gets automatically turned on if the deprecated optimize option gets set to performance.

DB_PORTABILITY_LOWERCASE convert names of tables and fields to lower case when using get*(), fetch*() and tableInfo()

This mode gets automatically turned on in the following databases if the deprecated option optimize gets set to portability:

  • oci8

DB_PORTABILITY_RTRIM right trim the data output by get*() fetch*()

DB_PORTABILITY_DELETE_COUNT force reporting the number of rows deleted

Some DBMS's don't count the number of rows deleted when performing simple DELETE FROM tablename queries. This portability mode tricks such DBMS's into telling the count by adding WHERE 1=1 to the end of DELETE queries.

This mode gets automatically turned on in the following databases if the deprecated option optimize gets set to portability:

  • fbsql
  • mysql
  • mysqli
  • sqlite

DB_PORTABILITY_NUMROWS enable hack that makes numRows() work in Oracle

This mode gets automatically turned on in the following databases if the deprecated option optimize gets set to portability:

  • oci8

DB_PORTABILITY_ERRORS makes certain error messages in certain drivers compatible with those from other DBMS's

  • mysql, mysqli: change unique/primary key constraints DB_ERROR_ALREADY_EXISTS -> DB_ERROR_CONSTRAINT
  • odbc(access): MS's ODBC driver reports 'no such field' as code 07001, which means 'too few parameters.' When this option is on that code gets mapped to DB_ERROR_NOSUCHFIELD. DB_ERROR_MISMATCH -> DB_ERROR_NOSUCHFIELD

DB_PORTABILITY_NULL_TO_EMPTY convert null values to empty strings in data output by get*() and fetch*(). Needed because Oracle considers empty strings to be null, while most other DBMS's know the difference between empty and null.

DB_PORTABILITY_ALL turn on all portability features

-----------------------------------------

Example 1. Simple setOption() example

  1. <?php
  2. $dbh->setOption('autofree', true);
  3. ?>

Example 2. Portability for lowercasing and trimming

  1. <?php
  2. $dbh->setOption('portability',
  3. DB_PORTABILITY_LOWERCASE | DB_PORTABILITY_RTRIM);
  4. ?>

Example 3. All portability options except trimming

  1. <?php
  2. $dbh->setOption('portability',
  3. DB_PORTABILITY_ALL ^ DB_PORTABILITY_RTRIM);
  4. ?>

int setOption (string $option, mixed $value)
  • string $option: option name
  • mixed $value: value for the option
tableInfo (line 1929)

Returns information about a table or a result set

The format of the resulting array depends on which $mode you select. The sample output below is based on this query:

    SELECT tblFoo.fldID, tblFoo.fldPhone, tblBar.fldId
    FROM tblFoo
    JOIN tblBar ON tblFoo.fldId = tblBar.fldId

  • null (default)
       [0] => Array (
           [table] => tblFoo
           [name] => fldId
           [type] => int
           [len] => 11
           [flags] => primary_key not_null
       )
       [1] => Array (
           [table] => tblFoo
           [name] => fldPhone
           [type] => string
           [len] => 20
           [flags] =>
       )
       [2] => Array (
           [table] => tblBar
           [name] => fldId
           [type] => int
           [len] => 11
           [flags] => primary_key not_null
       )
  • DB_TABLEINFO_ORDER <p>In addition to the information found in the default output, a notation of the number of columns is provided by the num_fields element while the order element provides an array with the column names as the keys and their location index number (corresponding to the keys in the the default output) as the values.</p> <p>If a result set has identical field names, the last one is used.</p>
       [num_fields] => 3
       [order] => Array (
           [fldId] => 2
           [fldTrans] => 1
       )
  • DB_TABLEINFO_ORDERTABLE <p>Similar to DB_TABLEINFO_ORDER but adds more dimensions to the array in which the table names are keys and the field names are sub-keys. This is helpful for queries that join tables which have identical field names.</p>
       [num_fields] => 3
       [ordertable] => Array (
           [tblFoo] => Array (
               [fldId] => 0
               [fldPhone] => 1
           )
           [tblBar] => Array (
               [fldId] => 2
           )
       )

The flags element contains a space separated list of extra information about the field. This data is inconsistent between DBMS's due to the way each DBMS works.

  • primary_key
  • unique_key
  • multiple_key
  • not_null
Most DBMS's only provide the table and flags elements if $result is a table name. The following DBMS's provide full information from queries:
  • fbsql
  • mysql
If the 'portability' option has DB_PORTABILITY_LOWERCASE turned on, the names of tables and fields will be lowercased.

  • return: an associative array with the information requested. If something goes wrong an error object is returned.
  • access: public
  • see: DB_common::setOption()
array tableInfo (object|string $result, [int $mode = null])
  • object|string $result: DB_result object from a query or a string containing the name of a table. While this also accepts a query result resource identifier, this behavior is deprecated.
  • int $mode: either unused or one of the tableInfo modes: DB_TABLEINFO_ORDERTABLE, DB_TABLEINFO_ORDER or DB_TABLEINFO_FULL (which does both). These are bitwise, so the first two can be combined using |.

Redefined in descendants as:
toString (line 129)

String conversation

  • access: private
string toString ()
_convertNullArrayValuesToEmpty (line 2023)

Convert all null values in an array to empty strings

  • access: private
void _convertNullArrayValuesToEmpty (array &$array)
  • array $array: the array to be de-nullified (passed by reference)
_rtrimArrayValues (line 2004)

Right trim all strings in an array

  • access: private
void _rtrimArrayValues (array &$array)
  • array $array: the array to be trimmed (passed by reference)

Documentation generated on Fri, 24 Dec 2004 13:01:44 +0000 by phpDocumentor 1.3.0RC3