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

pg_escape_string Dodaje znaki ucieczki do łańcucha znaków (stringa) używanego w zapytaniach


pg_escape_string ([ resource $polaczenie ], string $dane ) : string

pg_escape_string() dodaje znaki ucieczki do łańcucha, którego chcemy użyć w zapytaniu do bazy danych. Zwraca łańcuch z sekwencjami Escape w formacie PostgreSQL-a bez cudzysłowów. pg_escape_literal() jest bardziej zalecaną drogą zabezpieczenia parametrów SQL dla PostreSQL. Nie można używać funkcji addslashes() z PostreSQL. Jeśli typem kolumny jest bytea, trzeba użyć funkcji pg_escape_bytea() zamiast tej. Do zabezpieczenia identyfikatorów (np. nazw tabel i pól należy użyć funkcji pg_escape_identifier().


Funkcja wymaga PostgreSQL 7.2 lub nowszego.



Identyfikator połączenia do bazy danych. Gdy polaczenie nie zostało podane, domyślne połączenie jest użyte. Domyślnym połączeniem jest ostatnie połączenie stworzone przez pg_connect() lub pg_pconnect().


Łańcuch (ang. string) zawierający tekst bez sekwencji Escape.

Zwracane wartości

Łańcuch (ang. string) zawierający dane z sekwencjami Escape.

Rejestr zmian

Wersja Opis
5.2.0 Parametr polaczenie został dodany


Przykład #1 pg_escape_string() - przykład

// Połączenie do bazy danych
$polaczenie pg_connect('dbname=foo');
// Przeczytaj plik tekstowy (zawierający apostrofy i ukośniki wsteczne)
$dane file_get_contents('list.txt');
// Dodaj sekwencje Escape do danych
$z_escape pg_escape_string($dane);
// Wpisz to do bazy danych
pg_query("INSERT INTO korespondencja (nazwa, dane) VALUES ('Moj list', '{$z_escape}')");

Zobacz też:

  • pg_escape_bytea() - Dodaje znaki ucieczki do łańcucha dodającego do pola typu bytea

add a note add a note

User Contributed Notes 11 notes

strata_ranger at hotmail dot com
10 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.
ringerc at ringerc dot id dot au
6 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:

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

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.
Nathan Bruer
12 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() ( function.

for example:
= pg_escape_string(utf8_encode($_POST['my_data']));
14 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.
9 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:

= array('foo', 'bar');

"$a" == 'Array';
$a == 'Array';
$a . '' == 'Array';

14 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.
efjiolvwejlojfwel at mailinator dot com
2 years ago
Please, as a service to the Internet, add a note advising developers to use prepared statements and placeholders, and deprecate this function and its friends (but not pg_escape_identifier).
There is no valid reason to mix data and SQL into a single string before sending it to the RDBMS, and thus create the potential for SQL injection vulnerabilities. Hence, there is no need to escape data. Hence, there is no need for this function. It's confusing to offer developers functionality that they don't need and shouldn't use.
Gautam Khanna
13 years ago
Security methods which you use depend on the specific purpose. For those who dont know, take a look at the following built-in PHP functions:

strip_tags()            to remove HTML characters
(also see htmlspecialchars)

escapeshellarg()      to escape shell commands etc

mysql_real_escape_string()     to escape mySQL commands.


web dot expert dot panel at gmail dot com
johniskew2 at yahoo dot com
14 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:
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.
strata_ranger at hotmail dot com
9 years ago
This may seem obvious, but remember that pg_escape_string escapes values for use as string literals in an SQL query -- if you need to escape arbitrary strings for use as SQL identifiers (column names, etc.), there doesn't seem to be a PHP function for that so you'll have to do that escaping yourself.  (PostgreSQL has an in-database function, quote_ident(), that does this.)

This can be an issue if your database contains mixed-case (or otherwise unusual) column names and you have a class interface managing your database/query interactions (for connecting to different types of databases).  If you don't double-quote your column names then postgreSQL will match them case-insensitively, but will label the results in all-lowercase (which differs from MySQL).

For example:

// Plain column identifier
$res = pg_query("Select columnName from table");
$row = pg_fetch_assoc($res);

var_dump($row['columnName']); // Doesn't work (throws E_NOTICE)
var_dump($row['columnname']); // Works

// Escaped column identifier
$res = pg_query("Select \"columnName\" from table");
$row = pg_fetch_assoc($res);

var_dump($row['columnName']); // Works
var_dump($row['columnname']); // Doesn't
arunintellirise at gmail dot com
3 years ago
PostgreSQL is a powerful and an open source object relational database having more than 15 years of active development and a proven architecture with an emphasis on extensibility and standards compliance. PostgreSQL primary functions are to store data securely and return that data in response to requests from other software applications that has earned it a strong reputation for reliability, data integrity and correctness which runs on all major operating system including Linux, UNIX and Windows. PostgreSQL is a cross platform which is open source and its source code is available free of charge that is not controlled by any corporation or other private entity. PostgreSQL also supports storage of binary large objects including picture, sound or video along with handles workloads ranging from small single machine applications to large internet facing applications with lots of concurrent users­. PostgreSQL is highly scalable in the sheer quantity of data which support international character sets and multibyte character encodings.
if you know more aboutthis note then please visit on our website.
To Top