pg_escape_string

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_escape_string Экранирование спецсимволов в строке запроса

Описание

pg_escape_string(PgSql\Connection $connection = ?, string $data): string

Функция pg_escape_string() экранирует спецсимволы в строке запроса для базы данных. Она возвращает экранированную строку в формате PostgreSQL. Функция pg_escape_string() является наиболее предпочтительным способом экранирования SQL параметров для PostgreSQL, в то время как addslashes() не должна использоваться с PostgreSQL. Если тип столбца bytea, то должна использоваться функция pg_escape_bytea() вместо pg_escape_string. Функция pg_escape_identifier() должна использоваться для экранирования идентификаторов (например, имена таблиц или полей).

Замечание:

Функция поддерживается PostgreSQL версии 7.2 и выше.

Список параметров

connection

Экземпляр класса PgSql\Connection. Функция выберет соединение по умолчанию, если параметр connection не указали. Соединение по умолчанию — последнее соединение, которое установила функция pg_connect() или pg_pconnect().

Внимание

Начиная с PHP 8.1.0 выбор функцией соединения по умолчанию устарел.

data

Исходная экранируемая строка.

Возвращаемые значения

Возвращает строку, в которой экранированы все необходимые символы.

Список изменений

Версия Описание
8.1.0 Параметр connection теперь ожидает экземпляр класса PgSql\Connection; раньше параметр ожидал ресурс (resource).

Примеры

Пример #1 Пример использования pg_escape_string()

<?php
// Подключение к базе данных
$dbconn = pg_connect('dbname=foo');

// Чтение текстового файла (содержащего апострофы и обратные слеши)
$data = file_get_contents('letter.txt');

// Экранирование спецсимволов в строке
$escaped = pg_escape_string($data);

// Вставка в таблицу базы данных
pg_query("INSERT INTO correspondence (name, data) VALUES ('My letter', '{$escaped}')");
?>

Смотрите также

  • pg_escape_bytea() - Экранирует спецсимволы в строке для вставки в поле типа bytea

add a note

User Contributed Notes 7 notes

up
5
strata_ranger at hotmail dot com
14 years ago
Forthose curious, the exact escaping performed on the string may vary slightly depending on your database configuration.

For example, if your database's standard_conforming_strings variable is OFF, backslashes are treated as a special character and pg_escape_string() will ensure they are properly escaped. If this variable is ON, backslashes will be treated as ordinary characters, and pg_escape_string() will leave them as-is. In either case, the behavior matches the configuration of the database connection.
up
3
ringerc at ringerc dot id dot au
10 years ago
You should prefer to use pg_query_params, i.e. use parameterized queries, rather than using pg_escape_string. Or use the newer PDO interface with its parameterized query support.

If you must substitute values directly, e.g. in DDL commands that don't support execution as parameterized queries, do so with pg_escape_literal:

http://au1.php.net/manual/en/function.pg-escape-literal.php

Identifiers can't be used as query parameters. Always use pg_escape_identifier for these if they're substituted dynamically:

http://au1.php.net/manual/en/function.pg-escape-identifier.php

You should not need to change text encodings when using this function. Make sure your connection's client_encoding is set to the text encoding used by PHP, and the PostgreSQL client driver will take care of text encodings for you. No explicit utf-8 conversions should be necessary with a correctly set client_encoding.
up
2
Nathan Bruer
16 years ago
If your database is a UTF-8 database, you will run into problems trying to add some data into your database...

for securty issues and/or compatability you may need to use the: utf_encode() (http://php.net/utf8-encode) function.

for example:
<?php
$my_data
= pg_escape_string(utf8_encode($_POST['my_data']));
?>
up
0
ppp
13 years ago
pg_escape_string() won't cast array arguments to the "Array" string like php usually does; it returns NULL instead. The following statements all evaluate to true:

<?php
$a
= array('foo', 'bar');

"$a" == 'Array';
(string)
$a == 'Array';
$a . '' == 'Array';

is_null(pg_escape_string($a));
?>
up
0
johniskew2 at yahoo dot com
18 years ago
For those who escape their single quotes with a backslash (ie \') instead of two single quotes in a row (ie '') there has recently been a SERIOUS sql injection vulnerability that can be employed taking advantage of your chosen escaping method. More info here: http://www.postgresql.org/docs/techdocs.50
Even after the postgre update, you may still be limited to what you can do with your queries if you still insist on backslash escaping. It's a lesson to always use the PHP functions to do proper escaping instead of adhoc addslashes or magic quotes escaping.
up
0
meng
18 years ago
Since php 5.1 the new function pg_query_params() was introduced. With this function you can use bind variables and don't have to escape strings. If you can use it, do so. If unsure why, check the changelog for Postgres 8.0.8.
up
0
otix
18 years ago
Creating a double-tick is just fine. It works the same as the backslash-tick syntax. From the PostgreSQL docs:

The fact that string constants are bound by single quotes presents an obvious semantic problem, however, in that if the sequence itself contains a single quote, the literal bounds of the constant are made ambiguous. To escape (make literal) a single quote within the string, you may type two adjacent single quotes. The parser will interpret the two adjacent single quotes within the string constant as a single, literal single quote. PostgreSQL will also allow single quotes to be embedded by using a C-style backslash.
To Top