Unfortunately the params will not respect string representations of NULL or NOW(). If your code pushes these values, they be considered a string and inserted literally as "NULL" and "NOW()".
Ideally, there should be an additional parameter that you can assign to force this text as pgSQL functions/reserved words and not wrap them up as strings (assuming pgSQL's parameterized queries support this.
This same problem also occurs for comma lists used in "WHERE column IN (1,2,3,4)", params treats "1,2,3,4" as a string, not a list of numbers, and runs it with quotes also.
For debugging, I use this function to simulate params, keep in mind this is not 100% accurate, it only attempts to simulate the actual SQL that param queries create.
<?php
function pg_query_params_return_sql($query, $array)
{
$query_parsed = $query;
for ($a = 0, $b = sizeof($array); $a < $b; $a++)
{
if ( is_numeric($array[$a]) )
{
$query_parsed = str_replace(('$'.($a+1)), str_replace("'","''", $array[$a]), $query_parsed );
}
else
{
$query_parsed = str_replace(('$'.($a+1)), "'".str_replace("'","''", $array[$a])."'", $query_parsed );
}
}
return $query_parsed;
}
?>
pg_query_params
(PHP 5 >= 5.1.0)
pg_query_params — Посылает параметризованный запрос на сервер, параметры передаются отдельно от текста SQL запроса
Описание
$connection
], string $query
, array $params
)Посылает параметризованный запрос на сервер и ждет результат. Параметры передаются отдельно от строки запроса.
pg_query_params() подобна функции pg_query(), но предоставляет дополнительный функционал: параметры запроса можно передавать отдельно от строки запроса. pg_query_params() поддерживается на соединениях с серверами PostgreSQL версий 7.4 и выше. Функция не будет работать с серверами ранних версий.
Если используются параметры params, они заменяют
псевдопеременные $1, $2 и т.д. в строке запроса query.
Значение NULL в массиве параметров будет означать SQL NULL
в запросе.
Главное преимущество pg_query_params() перед
pg_query() заключается в том, что значения параметров могут
передаваться отдельно от строки запроса query. Это дает
возможность избежать утомительную и подверженную ошибкам процедуру экранирования
спецсимволов и заключения значений в кавычки. Однако, в отличие от
pg_query(), эта функция поддерживает только один SQL запрос
в передаваемой строке. (Он может содержать точку с запятой, но не более одной
непустой SQL команды.)
Список параметров
-
connection -
Ресурс подключения к базе данных PostgreSQL. Если параметр
connectionне задан, будет использовано подключение по умолчанию - последнее соединение, открытое функцией pg_connect() или pg_pconnect(). -
query -
Параметризованный SQL запрос. Должен содержать только одно выражение (несколько выражений разделенных точкой с запятой не поддерживаются). Если в запрос будут передаваться параметры, то они заменят псевдопеременные $1, $2 и т.д.
-
params -
Массив значений параметров запроса для замены псевдопеременных $1, $2 и т.д. в исходной строке запроса. Количество элементов массива должно точно совпадать с количеством псевдопеременных.
Возвращаемые значения
Ресурс результата запроса или FALSE в случае возникновения ошибки.
Примеры
Пример #1 Пример использования pg_query_params()
<?php
// Подключение к базе данных "mary"
$dbconn = pg_connect("dbname=mary");
// Найдем все магазины с названием "Joe's Widgets". Стоит отметить, что нет необходимости экранировать
// спецсимволы в строке "Joe's Widgets"
$result = pg_query_params($dbconn, 'SELECT * FROM shops WHERE name = $1', array("Joe's Widgets"));
// Для сравнения то же самое, используя функцию pg_query
$str = pg_escape_string("Joe's Widgets");
$result = pg_query($dbconn, "SELECT * FROM shops WHERE name = '{$str}'");
?>
Third parameter $params of pg_query_params() ignores nay part of the string values after a zero byte character - PHP "\0" or chr(0). That may be a result of serialize().
See https://bugs.php.net/bug.php?id=63344
Note that due to your locale's number formatting settings, you may not be able to pass a numeric value in as a parameter and have it arrive in PostgreSQL still a number.
If your system locale uses "," as a decimal separator, the following will result in a database error:
pg_query_params($conn, 'SELECT $1::numeric', array(3.5));
For this to work, it's necessary to manually convert 3.5 to a string using e.g. number_format.
(I filed this as bug #46408, but apparently it's expected behavior.)
You can't run multiple statements with pg_query_params, but you can still have transaction support without falling back to pg_query:
<?php
$connection = pg_connect("host=127.0.0.1 port=5432 dbname=foo user=bar password=baz");
pg_query($connection, 'DROP TABLE IF EXISTS example');
pg_query($connection, 'CREATE TABLE example (col char(1))');
pg_query($connection, 'INSERT INTO example (col) VALUES (\'a\')');
// 'SELECT col FROM example' in another session returns "a"
pg_query($connection, 'BEGIN');
pg_query_params($connection, 'UPDATE example SET col = $1', array('b'));
// 'SELECT col FROM example' in another session still returns "a"
pg_query_params($connection, 'UPDATE example SET col = $1', array('c'));
// 'SELECT col FROM example' in another session still returns "a"
pg_query($connection, 'COMMIT');
// 'SELECT col FROM example' in another session returns "c"
?>
pg_query and pg_query_params can be combined into a single function. This also removes the need to construct a parameter array for pg_query_params:
<?php
function my_query($conn, $query)
{
if(func_num_args() == 2)
return pg_query($conn, $query);
$args = func_get_args();
$params = array_splice($args, 2);
return pg_query_params($conn, $query, $params);
}
?>
Usage:
<?php
/* non-parameterized example */
my_query($conn, "SELECT $val1 + $val2");
/* parameterized example */
my_query($conn, "SELECT $1 + $2", $val1, $val2);
?>
Regarding boolean values, just typecast them as (integer) when passing them in your query -- '0' and '1' are perfectly acceptable literals for SQL boolean input:
- http://www.postgresql.org/docs/8.2/interactive/datatype-boolean.html
It is also safe to write your paramerized query in double-quotes, which allows you to mix constant values and placeholders in your query without having to worry about how whether PHP will attempt to substitute any variables in your parameterized string.
Of course this also means that unlike PHP's double-quoted string syntax, you CAN include literal $1, $2, etc. inside SQL strings, e.g:
<?php
// Works ($1 is a placeholder, $2 is meant literally)
pg_query_params("INSERT INTO foo (col1, col2) VALUES ($1, 'costs $2')", Array($data1));
// Throws an E_WARNING (passing too many parameters)
pg_query_params("INSERT INTO foo (col1, col2) VALUES ($1, 'costs $2')", Array($data1, $data2));
?>
When inserting into a pg column of type bool, you cannot supply a PHP type of bool. You must instead use a string "t" or "f". PHP attempts to change boolean values supplied as parameters to strings, and then attempts to use a blank string for false.
Example of Failure:
pg_query_params('insert into table1 (bool_column) values ($1)', array(false));
Works:
pg_query_params('insert into lookup_permissions (system) values ($1)', array(false ? 't' : 'f'));
If you need to provide multiple possible values for a field in a select query, then the following will help.
<?php
// Assume that $values[] is an array containing the values you are interested in.
$values = array(1, 4, 5, 8);
// To select a variable number of arguments using pg_query() you can use:
$valuelist = implode(', ', $values);
$query = "SELECT * FROM table1 WHERE col1 IN ($valuelist)";
$result = pg_query($query)
or die(pg_last_error());
// You may therefore assume that the following will work.
$query = 'SELECT * FROM table1 WHERE col1 IN ($1)';
$result = pg_query_params($query, array($valuelist))
or die(pg_last_error());
// Produces error message: 'ERROR: invalid input syntax for integer'
// It only works when a SINGLE value specified.
// Instead you must use the following approach:
$valuelist = '{' . implode(', ', $values . '}'
$query = 'SELECT * FROM table1 WHERE col1 = ANY ($1)';
$result = pg_query_params($query, array($valuelist));
?>
The error produced in this example is generated by PostGreSQL.
The last method works by creating a SQL array containing the desired values. 'IN (...)' and ' = ANY (...)' are equivalent, but ANY is for working with arrays, and IN is for working with simple lists.
If you are trying to replicate the function pg_query_params, you might also want to support NULL values. While is_int returns true for a NULL value, the formatting for the SQL.
function pg_query_params( $db, $query, $parameters ) {
// Escape parameters as required & build parameters for callback function
global $pg_query_params__parameters;
foreach( $parameters as $k=>$v ) {
if ( is_null($v) ) {
$parameters[$k] = 'NULL';
} else {
$parameters[$k] = ( is_int( $v ) ? $v : "'".pg_escape_string( $v )."'" );
}
}
$pg_query_params__parameters = $parameters;
// Call using pg_query
return pg_query( $db, preg_replace_callback( '/\$([0-9]+)/', 'pg_query_params__callback', $query));
}
This is a useful function for preventing SQL injection attacks, so, for those of us who are not yet able to upgrade to PHP5.1, here is a replacement function which works similarly on older versions of PHP...
<?php # Parameterised query implementation for Postgresql and older versions of PHP
if( !function_exists( 'pg_query_params' ) ) {
function pg_query_params__callback( $at ) {
global $pg_query_params__parameters;
return $pg_query_params__parameters[ $at[1]-1 ];
}
function pg_query_params( $db, $query, $parameters ) {
// Escape parameters as required & build parameters for callback function
global $pg_query_params__parameters;
foreach( $parameters as $k=>$v )
$parameters[$k] = ( is_int( $v ) ? $v : "'".pg_escape_string( $v )."'" );
$pg_query_params__parameters = $parameters;
// Call using pg_query
return pg_query( $db, preg_replace_callback( '/\$([0-9]+)/', 'pg_query_params__callback', $query ) );
}
}
// Example: pg_query_params( $db_resource, "SELECT * FROM table WHERE col1=$1 AND col2=$2", array( 42, "It's ok" ) );
?>
