php pg query params

pg_query_params

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_query_params — Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text

Description

Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.

Parameters

User-supplied values should always be passed as parameters, not interpolated into the query string, where they form possible SQL injection attack vectors and introduce bugs when handling data containing quotes. If for some reason you cannot use a parameter, ensure that interpolated values are properly escaped.

Values intended for bytea fields are not supported as parameters. Use pg_escape_bytea() instead, or use the large object functions.

Return Values

A query result resource on success or false on failure.

Examples

Example #1 Using pg_query_params()

// Connect to a database named «mary»
$dbconn = pg_connect ( «dbname=mary» );

See Also

User Contributed Notes 15 notes

You can’t run multiple statements with pg_query_params, but you can still have transaction support without falling back to pg_query:

Debugging parameterised queries can be tedious, if you want to paste the query directly into PSQL. Here is a trick that helps:

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:

If you need to provide multiple possible values for a field in a select query, then the following will help.

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.

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.

A note on type-juggling of booleans:
pg_query_params() and friends do seamless, automatic conversion between PHP-NULL and SQL-NULL and back again, where appropriate.
Hoever, everything else goes in (and comes out) as a string.
The following approach may be helpful when handling boolean fields:

//$row[] now contains booleans, NULLS, and strings.
?>

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:

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.)

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));

If one of the parameters is an array, (eg. array of ints being passed to a stored procedure), it must be denoted as a set within the array, not php array notation.

eg: var_dump output of 2 parms an integer and array of int
aaa is: Array
(
[0] => 1
[1] => <2,3>
)

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.

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.

# Parameterised query implementation for Postgresql and older versions of PHP

pg_query_params() *does* accept NULLs. They will automatically be transformed, correctly, into SQL NULL. Thus, for example:

//is equivalent to:
$result = pg_query ( «UPDATE tbl_example SET column_a = NULL column_b = ’42’)» ;

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.

Источник

pg_query

Описание

resource pg_query (resource connection, string query)

resource pg_query ( string query )

pg_query() возвращает результирующий ресурс запроса, если запрос может быть выполнен. Возвращает FALSE при неудаче или если соединение не является правильным. Детали ошибки можно запросить с помощью функции pg_last_error(), если соединение является правильным. pg_last_error() отправляет SQL-оператор в БД PostgreSQL, специфицированную connection-ресурсом. connection обязано быть правильным соединением, возвращённым из pg_connect() или pg_pconnect(). return-значение этой функции это результирующий ресурс запроса, используемый для доступа к результатам из других PostgreSQL-функций, таких как pg_fetch_array().

Примечание: connection это необязательный параметр для pg_query(). Если connection не установлен, используется соединение по умолчанию. Соединение по умолчанию это соединение, созданное функцией pg_connect() или pg_pconnect().

Хотя connection может быть опущен, это не рекомендуется, так как могут быть трудности с поиском багов в скрипте.

Примечание: эта функция вызывалась pg_exec().
pg_exec() всё ещё доступна из соображений совместимости, но советуем использовать новое имя.

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

The SQL statement or statements to be executed. When multiple statements are passed to the function, they are automatically executed as one transaction, unless there are explicit BEGIN/COMMIT commands included in the query string. However, using multiple transactions in one function call is not recommended.

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

A query result resource on success, or FALSE on failure.

Источник

pg_send_query

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

pg_send_query — Отправляет асинхронный запрос

Описание

Несмотря на то, что можно отправить несколько запросов за раз, их нельзя посылать, пока соединение занято. В противном случае, посланный запрос дождётся завершения предыдущего, сотрёт его результат и запустится сам. Таким образом вы потеряете данные результата предыдущего запроса.

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

Ресурс соединения с базой данных PostgreSQL.

Одно или несколько SQL-выражений, разделённых точкой с запятой.

Спецсимволы в строке запроса должны быть экранированы.

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

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

Примеры

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

= pg_connect ( «dbname=publisher» ) or die( «Не удалось подключиться» );

Результат выполнения данного примера:

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

User Contributed Notes 6 notes

pg_send_query would not stop your script from executing but it would stop the script from exiting.

= pg_connect ( ‘dbname=payroll’ );
pg_send_query ( ‘SELECT process_payroll()’ ); // Where process_payroll is a super long process
?>

You would still need to wait for the query to finish before the any display would be sent to the browser. And surprisingly, unlike pg_query this script would not generate the Maximum execution time error.

Regarding the failure to process them all now, then retrieve the results later, I found that all queries would return successfully if I added a further condition to your while loop in the «stack_query()» method.

By adding:
&& (pg_transaction_status($conn) === PGSQL_TRANSACTION_IDLE ) )

Every query executed with no errors.

Due to a bug, OLD API does not available with PHP 4.2.0 and 4.2.1.

PHP 4.2.2 will support OLD API again and will be kept long enough.

New API will be available PHP 4.2.0 to later versions.
yohgaki at php dot net
19-Jun-2002 04:00
Due to a bug, PHP 4.2.0 and 4.2.1 does not support pg_lo_import() old API. It’s fixed in PHP 4.2.2.

BTW, new API will be always available from PHP 4.2.0 to later versions. Older API will be kept long enough, also.
ceco at noxis dot net
15-May-2002 09:08
it works for me (php-4.2.1)

int pg_lo_import ( string pathname [, resource connection])

but
int pg_lo_import ( resource connection, string pathname )

don’t know the reason

If there is an error in one of your queries, the queries following it will not get executed, and there will *not* be an error message displayed. The only way I can think of to determine if an SQL error happened is to use pg_trace.

pg_send_query($connection,
«SELECT id FROM users;
SELECT * FROM customers;
[INVALID-SQL-STATEMENT];
SELECT name FROM countries;»);

$conn = pg_connect ( «host=’127.0.0.1′ dbname=’test’ user=’usertest’ password=’passtest'» );

header ( «Content-type: image/gif» );

Источник

pg_query_params не работает со слишком большим количеством аргументов

Я не уверен, почему это не удается, у меня есть два примера, это одна и та же функция, но один работает, а другой не работает. Я действительно хочу, чтобы тот, который не работает, работал, потому что он позволит мне поместить большую часть моего потенциально повторяющегося кода в одну функцию.

setItemDoesNotWork:

setItemWorks:

Я получаю вот такую ​​ошибку:

Ошибка:

2 ответа

Изменить:

Так что это небезопасно, есть ли простой способ обезопасить эту функцию от SQL-инъекции?

Количество параметров не вызывает никаких проблем с pg_query_params() (во всяком случае, не только с 5 параметрами), источником проблемы является ваш запрос.

Как говорится в сообщении об ошибке, синтаксический анализатор запросов ожидает не параметр в этой позиции, а имя таблицы.

Параметры запроса можно использовать только вместо буквальных значений (строки, числа, NULL и т. Д.). Имена баз данных, таблиц и полей, ключевые слова SQL, функции, операторы и другие элементы синтаксиса не могут быть заменены параметрами.

Вы должны указать имена таблиц и поля в запросе. Вот почему ваш метод setItemWorks() работает, а setItemDoesNotWork() терпит неудачу.

Существует очень веская причина, по которой pg_query_params() (и аналогичные функции для других СУБД) принимают параметры только вместо буквальных значений: запрос с использованием параметров: проанализированы сервером, и это должен быть правильный SQL.

Источник

pg_query_params

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_query_params — SQL コマンドとパラメータを分割してサーバーへ送信し、その結果を待つ

コマンドをサーバーに送信し、その結果を待ちます。パラメータを SQL コマンド とは別に渡すことが可能です。

pg_query_params() は pg_query() と似ていますが、追加の機能を有しています。それはパラメータ値が コマンド文字列と分離しているということです。 pg_query_params() は PostgreSQL 7.4 以降の接続でのみ サポートされます。それ以前のバージョンでは失敗します。

pg_query() に対する pg_query_params() の最大の利点は、パラメータの値を query 文字列から 分離できることです。そのため、退屈でエラーの元となりやすいクォート・ エスケープなどをしなくてもよくなります。 pg_query() と異なり、 pg_query_params() ではひとつの SQL コマンドしか実行できません(クエリ文字列にセミコロンを含めることは 可能です。しかしそれ以降にコマンドを続けることはできません)。

パラメータ

PostgreSQL データベース接続リソース。 connection が指定されていない場合はデフォルトの接続が使用されます。 デフォルトの接続は、直近の pg_connect() あるいは pg_pconnect() によって作成されたものです。

ユーザーから受け取った値は常にパラメータとして渡すべきです。 直接クエリ文字列に組み込んではいけません。そうしてしまうと、 SQL インジェクション 攻撃を受けてしまう可能性があります。また、クォート文字を含むデータの処理でバグの原因になります。 何らかの理由でパラメータが使えない場合は、値を 適切にエスケープするようにしましょう。

bytea フィールド用の値は、パラメータとして指定できません。 pg_escape_bytea() を使うか、ラージオブジェクト関数を使うようにしましょう。

成功した場合にクエリ結果リソース、失敗した場合に false を返します。

例1 pg_query_params() の使用法

// «mary»という名前のデータベースに接続
$dbconn = pg_connect ( «dbname=mary» );

User Contributed Notes 15 notes

You can’t run multiple statements with pg_query_params, but you can still have transaction support without falling back to pg_query:

Debugging parameterised queries can be tedious, if you want to paste the query directly into PSQL. Here is a trick that helps:

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:

If you need to provide multiple possible values for a field in a select query, then the following will help.

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.

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.

A note on type-juggling of booleans:
pg_query_params() and friends do seamless, automatic conversion between PHP-NULL and SQL-NULL and back again, where appropriate.
Hoever, everything else goes in (and comes out) as a string.
The following approach may be helpful when handling boolean fields:

//$row[] now contains booleans, NULLS, and strings.
?>

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:

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.)

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));

If one of the parameters is an array, (eg. array of ints being passed to a stored procedure), it must be denoted as a set within the array, not php array notation.

eg: var_dump output of 2 parms an integer and array of int
aaa is: Array
(
[0] => 1
[1] => <2,3>
)

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.

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.

# Parameterised query implementation for Postgresql and older versions of PHP

pg_query_params() *does* accept NULLs. They will automatically be transformed, correctly, into SQL NULL. Thus, for example:

//is equivalent to:
$result = pg_query ( «UPDATE tbl_example SET column_a = NULL column_b = ’42’)» ;

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.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *