PDO Reference
PDO API reference. PDO is the connection; PDOStatement is the prepared / executed query.
PDO methods
| Method | Returns |
|---|---|
__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
| Method | What 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
| Constant | Rows look like |
|---|---|
PDO::FETCH_ASSOC | Associative array (most common). |
PDO::FETCH_NUM | Numeric array. |
PDO::FETCH_BOTH | Both (default — wasteful). |
PDO::FETCH_OBJ | stdClass with column-named props. |
PDO::FETCH_CLASS | Instances of a class you provide. |
PDO::FETCH_KEY_PAIR | First col → second col as a map. |
PDO::FETCH_COLUMN | Just one column, as a list. |
Error modes
| Constant | Behaviour |
|---|---|
PDO::ERRMODE_SILENT | You must check returns. Avoid. |
PDO::ERRMODE_WARNING | PHP warning + return false. |
PDO::ERRMODE_EXCEPTION | Use 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->
()
camelCase; 11 chars.
Discussion
Loading…