Bound parameters: SQL without hand-escaped values
Values go to the database server as bound parameters, apart from the SQL text: a quote, a backslash, ' OR 1=1 --, emoji
or binary bytes are always data, never SQL, and no _es() is needed. The drivers mysqli, pdo_mysql,
pgsql, pdo_pgsql and sqlite bind natively; clickhouse has no binding and gets the same
statement with each value as an escaped literal. Everything here is an addition: SQL written with _es() keeps working as
before.
Raw SQL: query() and get_*() with values
// "?" placeholders, values in order
$user = db()->get('SELECT * FROM ' . db('user') . ' WHERE login = ? AND active = ?', [$login, 1]);
$name = db()->get_one('SELECT name FROM ' . db('user') . ' WHERE id = ?', [$id]);
db()->query('UPDATE ' . db('user') . ' SET name = ? WHERE id = ?', [$name, $id]);
// ":name" placeholders (one style per statement); an array expands to a list, an empty array to NULL
$rows = db()->get_all('SELECT * FROM ' . db('user') . ' WHERE id IN (:ids) AND group_id = :g', ['ids' => $ids, 'g' => $group]);
$pairs = db()->get_2d('SELECT id, name FROM ' . db('user') . ' WHERE id IN (?)', [$ids]);
// the other arguments (key name, cache) through db()->sql()
$rows = db()->get_all(db()->sql('SELECT * FROM ' . db('user') . ' WHERE login = ?', [$login]), 'login', false);
The array of values is the second argument of query(), query_num_rows(), get() /
query_fetch(), get_one(), get_2d(), get_all() / query_fetch_all() and
get_deep_array(); the remaining arguments then keep their defaults. db()->sql($sql, $values) makes the same
statement as an object that every one of them takes in place of the SQL text, with all their other arguments.
Values
| PHP value | sent as |
|---|---|
null | NULL |
int, bool | an integer (true is 1): LIMIT ? works |
float | a number (INF and NAN are refused) |
string, Stringable, a backed enum | a string, byte-exact |
DateTimeInterface | the string Y-m-d H:i:s |
db()->binary($bytes) | binary data for a BLOB / BYTEA column
(binary values) |
| an array | one placeholder per item (IN (?)), never nested |
A wrong number of values, a name without a value, a value without a placeholder, both placeholder styles in one statement or a
value of another type: the call returns false with a warning, like a failed query, and nothing is sent. A ? or
:name inside a quoted string, a quoted identifier or a comment is text; :: (a PostgreSQL cast) is no
placeholder; ?? is a literal ? (the PostgreSQL jsonb operators).
LIKE
// like_escape() puts "!" before %, _ and !; the ESCAPE clause is the same on MySQL, PostgreSQL and SQLite
$rows = db()->get_all('SELECT * FROM ' . db('user') . ' WHERE name LIKE ? ESCAPE \'!\'', ['%' . db()->like_escape($q) . '%']);
The query builder: bind()
By default the builder puts values into the SQL text as they are (escape them with _es()). After
bind() every value given from then on is a bound parameter: pass raw values, never _es() ones (they would be
stored with their backslashes). Call it before the first value.
$user = db()->from('user')->bind()->where('login', '=', $login)->get();
$list = db()->from('user')->bind()->where('id', 'in', $ids)->where_raw('name LIKE ? OR email = ?', [$like, $email])->get_all();
db()->table('user')->bind()->where('id', '=', $id)->update(['name' => $name, 'last_login' => time()]);
db()->table('user')->bind()->insert(['login' => $login, 'name' => $name]);
db()->from('user')->bind()->where('id', '=', $id)->delete();
- In
bind()modewhere('col', $op, $value)with a plain column, a comparison operator (=,!=,<>,<,>,<=,>=) and a string or number compares exactly:%and*do not turn it into LIKE, a comma does not make a list, and''or0stay values (withoutbind(), and in the two-argument formwhere('col', $value), the old rules remain: such values give LIKE, a list or no condition). where_raw($sql, $values)takes placeholders in every mode: withoutbind()the values become escaped literals in the SQL text, with it bound parameters.- In
bind()modesql()(and$as_sql,['sql' => true]) return ayf_db_sqlobject: run it withdb()->query()/get_*(), or use it as a string (logs, display), which gives the SQL with escaped literals. - A subquery of a
bind()builder in anotherbind()builder (where_exists(),subquery()) keeps its values bound. - Column and table names are not values: they are quoted by the builder (
escape_key()) and must never come from the request without a check against a list of allowed names.
Names from the request: ident(), order_dir() and the allow-listed builder methods
A column or table name cannot be bound. When it comes from the request (a sort column, a direction, a list of columns to show), check it against the names the page allows. The helpers never fall back to the raw input:
$allowed = ['id', 'login', 'add_date', 'u.name'];
// the quoted name (`login` on MySQL, "login" on PostgreSQL) or false when it is not literally in the list
$col = db()->ident($_GET['sort'] ?? '', $allowed);
// 'ASC' or 'DESC' (trimmed, any case); anything else gives the default, here 'DESC'
$dir = db()->order_dir($_GET['dir'] ?? '', 'DESC');
if ($col !== false) {
$rows = db()->get_all('SELECT * FROM ' . db('user') . ' ORDER BY ' . $col . ' ' . $dir . ' LIMIT ?', [50]);
}
// the builder: a name not in the list is skipped, nothing is added and the builder is returned as it was
$rows = db()->from('user')->order_by_allowed($_GET['sort'] ?? '', $_GET['dir'] ?? '', $allowed)->order_by('id')->get_all();
$rows = db()->from('user')->select_allowed((array) ($_GET['cols'] ?? []), $allowed)->get_all();
ident($name, array $allowed): only a string or an int is a name, compared strictly with the strings of the list;u.namepasses only whenu.nameitself is in the list, and each part is quoted. Arrays, objects,nulland anything not in the list givefalse.order_dir($dir, $default = 'ASC'): a default other thanDESC(any case) isASC.order_by_allowed($field, $dir, array $allowed)andselect_allowed(array $fields, array $allowed)add to whatorder_by()/select()added before.select_allowed()uses the values of$fields(keys are ignored); when none passes it adds nothing, so the query selects*unless an earlierselect()set columns: check the list first where*must not happen.order_by()andselect()themselves do not change: they pass an expression (anything with a character other than a letter, digit,_or.) through as it is, so they must never get request data.
Migrating a site
Binding is opt-in and stays so: SQL with _es() / (int) keeps working, move it when you touch the code.
make check-site SITE=/path/to/site lists the calls whose SQL has values concatenated in as the warning
sql_concat_value (file:line, escaped for _es() / (int) values, unclassified
for a variable or call it cannot tell; up to 5 lines and a count per file, ARGS=--sql-all or
.dev/python-tools/check-site.py --sql-all for every line). It never changes the exit status. Table and column names in the
SQL are not reported: they cannot be bound (use ident() above).
// before
$row = db()->get('SELECT * FROM ' . db('news') . ' WHERE id = ' . (int) $id . " AND lang = '" . _es($lang) . "'");
// after
$row = db()->get('SELECT * FROM ' . db('news') . ' WHERE id = ? AND lang = ?', [$id, $lang]);
- Drop the
_es()of a value you bind, or it is stored with its backslashes. - mysqli returns the columns of a bound statement with their types (an
INTcolumn as a PHP int); the same SQL without values returns strings. Code that compares a column strictly (=== '1') or passes rows on to code that does casts the row:array_map(fn ($v) => $v === null ? null : (string) $v, $row). - A site class that overrides
query($sql)of the database must pass the extra arguments on (parent::query(...func_get_args())): an override that drops them runs the statement with its placeholders unbound, a query error.
More before / after examples (the builder, where_raw(), IN lists): docs/UPGRADING.md, "Moving site SQL to
bound parameters".
Notes
- pdo_mysql emulates prepared statements in the client (PDO's default), with the escaping of the connection's charset: one round trip per statement. mysqli, pgsql, pdo_pgsql and SQLite prepare on the server or in the library: mysqli makes one extra round trip per statement.
- The result cache of
get_*()(ALLOW_CACHE_QUERIES) keys a bound statement by its SQL and its values with their types. - The debug console and the query log show the SQL with its placeholders followed by the values (
-- [..]), binary values as their length. - Some statements cannot be prepared on MySQL (a few administrative ones, several statements in one string): send those without values.