pg_quote − escapes a string for inclusion into SQL statements
pg_quote [-null] [connection] string
pg_quote quotes a string and escapes single quotes and backslashes within the string, making it safe for inclusion into SQL statements.
If a connection is provided, the connection is used to customize the quoting process for the database referenced by the connection.
If the [-null] option is provided, then if the text matches the null string (either the empty string, or the null string specified in the connection) then the SQL keyword NULL is returned, rather than a quoted string.
If you’re doing something like
pg_exec $conn
"insert into foo values (’$name’);"
and name contains text includeng an unescaped single quote,
such as Bob’s House, at best the insert will fail, and
at worst your software will be exploited via an SQL
injection attack. Passing value strings through
pg_quote will properly quote them for insertion into
SQL commands.
pg_exec $conn
"insert into foo values ([pg_quote $name]);"
...will make sure that any special characters that occur in
name, such as single quote or backslash, will be properly
quoted.
string |
The string to be escaped. |
Returns the string, escaped for inclusion into SQL queries. Note that it adds a set of single quotes around the outside of the string as well.
In most cases, with recent versions of SQL, it is better to use the native parameter insertion capabilities of the SQL server and protocol. If you are using a version of PostgreSQL more recent then 7.4, consider the optional parameter arguments to pg_exec and pg_sendquery, and the paramarray option to pg_exec, pg_sendquery, and pg_select.