Escaping values for raw SQL
_es($value) (db()->es()) turns a value into the body of a SQL string literal: you write the quotes around
it. null and the string NULL give NULL, an int / float / bool a number, an array is escaped item by
item. insert_safe() and update_safe() call it for you. Use it only inside single quotes: between
double quotes MySQL with NO_BACKSLASH_ESCAPES lets a " end the literal (no escaping can prevent it), and
PostgreSQL and SQLite read "..." as a column name (make check-site reports es_double_quoted).
Numbers need (int) / (float), table and column names an allow-list.
$sql = 'SELECT id FROM ' . db('user') . " WHERE login = '" . _es($login) . "'";
// LIKE: _es() does not escape % and _ (they are not special in a literal); add the LIKE escapes yourself when the user should not use them
$like = addcslashes($q, '%_\\');
$sql = 'SELECT id FROM ' . db('news') . " WHERE title LIKE '%" . _es($like) . "%'";
Prepared statements (parameter binding) need no escaping at all; insert_binary() / update_binary() use them
(see Binary values in the database). _es() is for SQL built as text. New code should pass values as
bound parameters instead: db()->query('... WHERE id = ?', [$id]), the
builder's bind().
What the escaping depends on
The same bytes are a safe literal on one server and an injection on another, so _es() follows the rules of the
connection, its dialect profile:
| Database | Rules |
|---|---|
| MySQL / MariaDB | A backslash before \ ' " NUL \n \r ^Z; with sql_mode
NO_BACKSLASH_ESCAPES only the quote is doubled (''). With the client charsets gbk, big5,
sjis, cp932, gb18030 a backslash can be the second byte of a character, so the value is read
character by character (the 0xBF27 attack). |
| PostgreSQL | The quote is doubled; with standard_conforming_strings off (not the default since 9.1) the
backslash too. A text value cannot hold NUL: it ends there. |
| SQLite | The quote is doubled; NUL is spliced in as ' || char(0) || ', so it works only between single
quotes (between double quotes SQLite would read an identifier). |
With a connection
Once the connection is open, _es() uses the driver's own escape function: mysqli_real_escape_string(),
PDO::quote() (pdo_mysql, pdo_pgsql), pg_escape_string(). They run locally (no round trip) and follow the
server mode as it is now: a SET sql_mode or SET standard_conforming_strings sent any way, through
db()->query(), multi_query() or the raw link, and a SET undone by ROLLBACK. One limit
comes from the drivers: the charset is the one the connection was opened with (DB_CHARSET, mysqli_set_charset());
a raw SET NAMES to another charset is not seen, so change the charset with DB_CHARSET, never with
SET NAMES.
db()->escape_profile() reports the profile, for example
['family' => 'mysql', 'charset' => 'utf8mb4', 'no_backslash_escapes' => false, ...]. It is read from the server on
first use (one query on mysqli, pdo_mysql and pdo_pgsql; libpq's status on pgsql, always live) and read again after SQL through
db() that may change the session (anything but a plain read or write, set_config()). A value it cannot read is
null and is not kept.
Before the first connection
_es() does not need a connection. Before the first one the charset comes from DB_TYPE /
DB_CHARSET (mysqli always connects as utf8mb4), and the server mode (NO_BACKSLASH_ESCAPES,
standard_conforming_strings) is not known (null in the profile). A value without a backslash (MySQL:
and without a quote of either kind) is the same in every mode and between either quote: _es() returns it as it is,
without connecting (a raw newline or NUL is valid inside a literal).
Any other value has no such form. A backslash must be written \\ with backslash escapes on, and \\ is
stored as two backslashes with them off. On
MySQL, which also reads "..." as a string, '' is one quote between single quotes but two between double
quotes. So _es() opens the connection for it (as the old driver mode always did) and uses the driver's escape.
With no connection possible (it failed, RECONNECT_NUM_TRIES is 0, a reconnect lock), or with an
ESCAPE_PROFILE that does not give the mode, it doubles the quote and the backslash and writes MySQL's " as
\": never the end of a single-quoted literal in either mode (nor of a double-quoted one with backslash escapes on), exact with backslash escapes on (MySQL with the drivers' empty
sql_mode, PostgreSQL with standard_conforming_strings off), a backslash stored twice otherwise. With
CONNECTION_REQUIRED the exception for a failed connection therefore comes from _es() only for such a value, and
otherwise from the first query. Set db.ESCAPE_PROFILE when SQL is built for a known server without connecting.
Settings
| Setting | Default | What it does |
|---|---|---|
db.ESCAPE_MODE | 'dialect' | dialect: escaping never needs a
connection; with one open, the driver's escape (see above). driver (the default before this release, the opt-out): always
connect first, then the driver's escape. |
db.ESCAPE_PROFILE | [] | Profile keys laid over the one read from the connection. Set
the whole profile to escape by the rules of a known server (SQL written to a file for another server): ['family' => 'pgsql',
'standard_conforming_strings' => true]; with it, _es() never connects and always uses these rules. |
db.ESCAPE_INVALID_UTF8 | 'keep' | Invalid UTF-8 (a cut character, a stray byte, an
encoded surrogate) in a UTF-8 database: keep passes it on (MySQL stores ? or, for an encoded surrogate on
MariaDB, the bytes; PostgreSQL refuses the query); scrub replaces each invalid sequence by U+FFFD first. Do not turn it on
where binary data still goes through _es(). |
db.DB_UTF8_AS_UTF8MB4 | true | A DB_CHARSET of utf8 connects as
utf8mb4 (utf8 is utf8mb3: emoji were stored as ???? by pdo_mysql). |
JSON and multibyte text
JSON text from json_encode() goes through _es() like any string: its \u00e9, \",
\\ and \n are stored as written. Use a utf8mb4 column (and connection) for emoji. The server
checks JSON itself: a lone surrogate escape (\ud83d without its pair) is refused by a MariaDB JSON column and
by PostgreSQL jsonb, \u0000 by jsonb; PostgreSQL json keeps the text as it is.