Introduction
Run SQL on the database connection
Fegg\Database\Pdo builds and runs SQL on top of PHP's PDO. Fegg\Model uses it for every query.
Usually you don't need this class: use Fegg\Model, which also checks names, applies the visible flag and pages results. Use Pdo for raw SQL the model cannot express.
The Fegg 4 class name DB_pdo (and $this->getClass('DB_pdo')) still works through a compatibility layer, but every use is reported as Fegg deprecated: ... in the PHP error log, and it will be removed in Fegg 6.
How to use
use Fegg\Database\Pdo;
$db = new Pdo();
// Raw SQL with ? placeholders
$rows = $db->setQuery(
'SELECT category, count(*) AS n FROM cms_news WHERE valid = 1 GROUP BY category HAVING n > ?',
array(1)
)->execute()->all();
// Or build the query
$rows = $db->setWhere('category = ?', 2)->setOrder('post_date DESC')->select('cms_news')->execute()->all();
A query is built with the set* methods and a build method (select, count, insert, update, delete ...), or written with setQuery. execute runs it, then all, one, getAffectedRow or getLastIndexId read the result. After execute() the built query is forgotten, so each query starts clean.
Automatic queries
Queries built with the build methods get the automatic parts of database_regular_use_query.php (see Configuration): valid = 1 on SELECT and count, created / modified / valid on INSERT and modified on UPDATE. Queries written with setQuery() get nothing added.
Values and placeholders
- Values are always bound to
?placeholders. Integers and booleans are bound as integers,nullas NULL, everything else as strings (socount(*) > ?works on SQLite). - In setWhere, setHaving and setOn, an array bound to one placeholder expands it:
id = ?andid IN (?)becomeid IN (?, ?, ...),<>/!=/NOT INbecomeNOT IN,LIKE ?becomes(... LIKE ? OR ... LIKE ?)andNOT LIKE ?becomes(... NOT LIKE ? AND ...). An empty array matches no row (=,IN,LIKE) or every row (<>,NOT IN,NOT LIKE). An array on any other operator throwsInvalidArgumentException. - A
?inside a quoted string literal ('?') is not a placeholder. - Table, column and ORDER BY text given to the
set*methods is written into the SQL as it is: never put user input in it.
Errors
A failed connection or query throws Fegg\Database\QueryException (a RuntimeException). Its message ends with the SQL with its values filled in, for example no such column: nope (SQL: SELECT nope FROM cms_news WHERE title = 'it''s'). getSql() returns the SQL with its ? placeholders and getParameters() the values. Uncaught, it becomes an HTTP 500 and is written to the PHP error log and the application log. Fegg 4 printed the error (to developer IPs only) and called exit instead.
use Fegg\Database\QueryException;
try {
$db->setQuery($sql, $params)->execute();
} catch (QueryException $e) {
// e.g. a duplicate key
error_log($e->getMessage());
}
Connections and transactions
- Connections are opened once per DSN and user name and shared by every
Pdoinstance and every model. - SELECT and PRAGMA queries run on a slave, other queries on the master (see Configuration). masterServer and slaveServer choose the server for the next query.
- beginTransaction opens a transaction on the master. Until commit or rollBack, every query of every instance and every model runs inside it. Model::transaction does this for you.
Methods
Pdo::__construct
Pdo class constructor
Pdo::select
Set select query
Pdo::count
Set select count query
Pdo::insert
Set insert query
Pdo::update
Set update query
Pdo::delete
Set delete query
Pdo::truncate
Set truncate query
Pdo::createTable
Set create table query
Pdo::createIndex
Set create index query
Pdo::alterAddColumn
Set create alter add column query
Pdo::alterRenameTo
Set create alter rename to query
Pdo::dropTable
Set create drop table query
Pdo::dropIndex
Set create drop index query
Pdo::pragma
Set pragma query
Pdo::setGroup
Set group query
Pdo::setItem
Set query item values
Pdo::setValues
Set the values to write from an associative array
Pdo::setIncrement
Add to a numeric column in an UPDATE
Pdo::setLimit
Set limit value
Pdo::setOrder
Set order value
Pdo::setQuery
Set query string directly
Pdo::setWhere
Set where condition
Pdo::setHaving
Set having condition
Pdo::setJoin
Set join table
Pdo::setOn
Set on query for joined table
Pdo::disabledRegularUseQuery
Disable automatic append query flag
Pdo::unsetRegularUseQuery
Disable automatic append query for a current query flag
Pdo::unsetRegularUseQueryForTable
Disable automatic append query of the table for a current query flag
Pdo::reset
Forget the query being built
Pdo::setInitQueryFlag
Enable reset query flag
Pdo::unsetInitQueryFlag
Disable reset query flag
Pdo::execute
Execute built query
Pdo::compile
Compile built query (not execute)
Pdo::all
Get all the result of executed select query
Pdo::one
Shift the result of executed select query
Pdo::id
Get the specific column's list of executed select query
Pdo::simpleArray
Get the specific column's key and value array of executed select query
Pdo::getAffectedRow
Get affected row number of executed update query
Pdo::getLastIndexId
Get the last inserted id of executed insert query
Pdo::getLastQuery
Get the last executed query for debugging
Pdo::getLastQueryDebug
Get the last executed query and parameter separately for debugging
Pdo::getQuery
Get the built query
Pdo::getParam
Get the values of the built query
Pdo::getReturnCode
Get return code of the last executed query
Pdo::masterServer
Connect to master server
Pdo::slaveServer
Connect to slave server
Pdo::close
Disconnect from the database
Pdo::closeAll
Drop every shared connection
Pdo::beginTransaction
Begin a transaction
Pdo::commit
Commit the open transaction
Pdo::rollBack
Roll back the open transaction
Pdo::inTransaction
Check whether a transaction is open