iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PDO Reference

PDO API reference. PDO is the connection; PDOStatement is the prepared / executed query.

PDO methods

MethodReturns
__construct($dsn, $u, $p, $opts)Connect.
query($sql, $fetchMode = null)One-shot select. Returns PDOStatement.
exec($sql)One-shot non-select. Returns row count.
prepare($sql, $options = [])Returns PDOStatement.
lastInsertId($name = null)Latest auto-id.
beginTransaction() / commit() / rollBack()Transactions.
inTransaction()True if a tx is open.
getAttribute($attr) / setAttribute($attr, $v)Tweak driver options.
quote($s, $type = PDO::PARAM_STR)Escape for SQL — prefer prepared instead.

PDOStatement methods

MethodWhat it does
execute($params = [])Run with bound params.
bindValue($n, $v, $type)Bind a literal.
bindParam($n, &$v, $type)Bind by reference.
fetch($mode = null)One row.
fetchAll($mode = null)All rows.
fetchColumn($col = 0)One value from one column.
fetchObject($class = stdClass::class)One row as object.
rowCount()Affected/returned row count.
columnCount()Number of columns in result.
closeCursor()Release the cursor for reuse.

Fetch modes

ConstantRows look like
PDO::FETCH_ASSOCAssociative array (most common).
PDO::FETCH_NUMNumeric array.
PDO::FETCH_BOTHBoth (default — wasteful).
PDO::FETCH_OBJstdClass with column-named props.
PDO::FETCH_CLASSInstances of a class you provide.
PDO::FETCH_KEY_PAIRFirst col → second col as a map.
PDO::FETCH_COLUMNJust one column, as a list.

Error modes

ConstantBehaviour
PDO::ERRMODE_SILENTYou must check returns. Avoid.
PDO::ERRMODE_WARNINGPHP warning + return false.
PDO::ERRMODE_EXCEPTIONUse this. Throws PDOException.
Tip: The connect-time options array is the right place to set ATTR_ERRMODE, ATTR_DEFAULT_FETCH_MODE, and ATTR_EMULATE_PREPARES — done once, applied everywhere.

Example

Example
<?php
// PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
// fetch(PDO::FETCH_ASSOC), fetchAll, fetchColumn
// prepare, execute, bindValue, bindParam, rowCount
// lastInsertId, beginTransaction, commit, rollBack
echo 'PDO is the standard DB abstraction layer.';
Try it Yourself »

Exercise

Fetch one column value.

$stmt-> ()

Test yourself

Q1. For one value use…
Q2. For first-column → second-column mapping use…
Q3. PDO::ATTR_EMULATE_PREPARES should be…

Discussion

Loading…