Constructor
DB_common
DB_common
()
Returns the affected rows of a query
mixed
affectedRows
()
Redefined in descendants as:
enable automatic Commit
mixed
autoCommit
([boolean $onoff = false])
Redefined in descendants as:
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
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
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 !
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
starts a Commit
mixed
commit
()
Redefined in descendants as:
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:
Deletes a sequence
int
dropSequence
(string $seq_name)
-
string
$seq_name: name of the sequence to be deleted
Redefined in descendants as:
Map native error codes to DB's portable ones
Requires that the DB implementation's constructor fills in the $errorcode_map property.
int
errorCode
(mixed $nativecode)
-
mixed
$nativecode: the native error code, as returned by the backend database extension (string or integer)
Redefined in descendants as:
Map a DB error code to a textual message. This is actually just a wrapper for DB::errorMessage()
string
errorMessage
(integer $dbcode)
-
integer
$dbcode: the DB error code
Returns an errormessage, provides by the database
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.
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:
Executes a DB statement prepared with prepare()
Example 1.
- <?php
- $sth = $dbh->prepare('INSERT INTO tbl (a, b, c) VALUES (?, !, &)');
- $data = array(
- "John's text",
- "'it''s good'",
- 'filename.txt'
- );
- $res =& $dbh->execute($sth, $data);
- ?>
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:
Emulates the execute statement, when not supported
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.
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
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:
Fetch all the rows returned from a query
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
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.
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.
Fetch a single column from a result set and return it as an indexed array
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.
list internal DB info valid values for $type are db dependent, often: databases, users, view, functions
mixed
getListOf
(string $type)
-
string
$type: type of requested info
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.
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.
Returns the value of an option
mixed
getOption
(string $option)
-
string
$option: option name
Fetch the first row of data returned from a query
Takes care of doing the query and freeing the results when finished.
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
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
Returns the query needed to get some backend info
string
getSpecialQuery
(string $type)
-
string
$type: What kind of info you want to retrieve
Redefined in descendants as:
Generates a limited query
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.
This method is used by backends to alter limited queries
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:
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.
the
modifyQuery
(string $query)
-
string
$query: query to modify
Redefined in descendants as:
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:
Returns the number of rows in a result object
mixed
numRows
(object DB_Result $result)
-
object DB_Result
$result: the result object to check
Redefined in descendants as:
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.
- <?php
- $sth = $dbh->prepare('INSERT INTO tbl (a, b, c) VALUES (?, !, &)');
- $data = array(
- "John's text",
- "'it''s good'",
- 'filename.txt'
- );
- $res = $dbh->execute($sth, $data);
- ?>
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.
mixed
prepare
(string $query)
-
string
$query: query to be prepared
Redefined in descendants as:
Tell whether a DB implementation or its backend extension supports a given feature
bool
provides
(array $feature)
-
array
$feature: name of the feature (see the DB class doc)
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:
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:
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.
string
quoteIdentifier
(string $str)
-
string
$str: identifier name to be quoted
Redefined in descendants as:
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.
mixed
quoteSmart
(mixed $in)
-
mixed
$in: data to be quoted
Redefined in descendants as:
DEPRECATED: Quotes a string so it can be safely used within string delimiters in a query
string
quoteString
(mixed $string)
Communicate an error and invoke error callbacks, etc
Basically a wrapper for PEAR::raiseError without the message string.
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.
starts a rollback
mixed
rollback
()
Redefined in descendants as:
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.
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:
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:
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:
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
- <?php
- $dbh->setOption('autofree', true);
- ?>
Example 2. Portability for lowercasing and trimming
- <?php
- $dbh->setOption('portability',
- DB_PORTABILITY_LOWERCASE | DB_PORTABILITY_RTRIM);
- ?>
Example 3. All portability options except trimming
- <?php
- $dbh->setOption('portability',
- DB_PORTABILITY_ALL ^ DB_PORTABILITY_RTRIM);
- ?>
int
setOption
(string $option, mixed $value)
-
string
$option: option name
-
mixed
$value: value for the option
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:
If the 'portability' option has
DB_PORTABILITY_LOWERCASE turned on, the names of tables and fields will be lowercased.
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:
String conversation
string
toString
()
Convert all null values in an array to empty strings
void
_convertNullArrayValuesToEmpty
(array &$array)
-
array
$array: the array to be de-nullified (passed by reference)
Right trim all strings in an array
void
_rtrimArrayValues
(array &$array)
-
array
$array: the array to be trimmed (passed by reference)