PHP 8.3.4 Released!

pg_convert

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

pg_convert Преобразовывает значения ассоциативного массива в вид, который соответствует SQL-запросам

Описание

pg_convert(
    PgSql\Connection $connection,
    string $table_name,
    array $values,
    int $flags = 0
): array|false

Функция pg_convert() проверяет и преобразовывает значения массива values в значения, которые соответствуют формату SQL-выражения. Предварительное условие функции pg_convert() — таблица table_name должна существовать, а количество колонок в таблице должно быть не меньше количества значений в массиве values. Имена колонок в таблице table_name должны совпадать с ключами массива values, типы данных значений массива также должны совпадать с типами данных колонок. В случае удачной конвертации функция возвращает массив преобразованных значений, иначе возвращает false.

Замечание:

Логические значения преобразовываются в логический тип СУБД PostgreSQL. Поддерживаются также строковые представления логического значения. Значение null преобразовывается в значения NULL СУБД PostgreSQL.

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

connection

Экземпляр класса PgSql\Connection.

table_name

Имя таблицы базы данных.

values

Данные для преобразования.

flags

Одна или комбинация констант PGSQL_CONV_IGNORE_DEFAULT, PGSQL_CONV_FORCE_NULL или PGSQL_CONV_IGNORE_NOT_NULL.

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

Функция возвращает массив (array), который содержит преобразованные данные или false в случае ошибки.

Ошибки

Функция выбрасывает исключение ValueError или TypeError, если значение или тип поля не соответствует правильному типу СУБД PostgreSQL.

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

Версия Описание
8.3.0 Функция теперь выбрасывает исключение ValueError или TypeError, если значение или тип поля не соответствуют правильному типу СУБД PostgreSQL; раньше функция выдавала ошибку уровня E_WARNING.
8.1.0 Параметр connection теперь ожидает экземпляр класса PgSql\Connection; раньше параметр ждал ресурс (resource).

Примеры

Пример #1 Пример использования функции pg_convert()

<?php

$dbconn
= pg_connect('dbname=foo');

$tmp = array(
'author' => 'Joe Thackery',
'year' => 2005,
'title' => 'My Life, by Joe Thackery'
);

$vals = pg_convert($dbconn, 'authors', $tmp);

?>

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

  • pg_meta_data() - Получение метаданных таблицы
  • pg_insert() - Заносит данные массива в таблицу базы данных
  • pg_select() - Выбирает записи из базы данных
  • pg_update() - Обновление данных в таблице
  • pg_delete() - Удаляет записи

add a note

User Contributed Notes 5 notes

up
2
Anonymous
19 years ago
The only options that I see are:

PGSQL_CONV_IGNORE_DEFAULT - Do not use DEAFULT value by removing field from returned array
PGSQL_CONV_FORCE_NULL - Convert to NULL if string is null string
PGSQL_CONV_IGNORE_NOT_NULL - Ignore NOT NULL constraints

These are constants, so don't quote them or anything.
up
0
gorhas at gmail dot com
9 years ago
There is a problem when using interval.
If in the array
"time_pause" => '00:30:00'
and time_pause is an interval
the insert fails
pg_insert(): '00:30:00' does not match with '^(@?[ \t]+)?((([-+]?[ \t]+)?[0-9]+(\.[0-9]*)?[ ...
up
0
dharana at dharana dot net
20 years ago
I've found "options" possible values:

PG_CONV_CHECK - check only
PG_CONV_STRICT - raise warning for non fatal error
PG_CONV_QUOTE - add quote around values for vchar, text datetime.
PG_CONV_SLASH - add slashes if it needed.
PG_CONV_NULLCHK - check values are defined for NOT NULL fields.
PG_CONV_NO_DEFAULT - ignore default value even if value is empty string.
up
-1
VLroyrenn
5 years ago
Another thing that's not well documented is that (as of PHP 7.0/7.1) pg_convert doesn't like non-scalar types and will fail (but not throw just emit an E_WARNING and return false) if you pass it anything other than a string or a number, including an array or something like a DateTime. If you want to insert those types, you actually have to convert those yourself.

Also, somewhat surprisingly, $table_name is not compatible with the output of pg_​escape_​identifier, or seemingly any other kind of escaping.
up
-1
Hayley Watson
6 years ago
This will only apply the appropriate escaping and such appropriate for embedding the PHP value into an SQL statement.

It does (by default) check for nulls when the column is marked NOT NULL, and it will complain about trying to convert strings for an integer column (floats will be truncated).

Beyond the barest checking of syntax, however, it does NOT verify that the given value is a legitimate value for the column type.

<?php
// Assuming smallints.smallintis a smallint (-32768..32767) type column
foreach([-1234,
1234,
0,
32767,
-
32768,
32768, // bogus value for smallint type
45.8, // gets truncated to 45
400000, // bogus value for smallint type
] as $smallint)
{
$tmp = ['smallint' => $smallint];
$vals = pg_convert($dbconn, 'smallints', ['smallint' => $smallint]);
echo
$vals['"smallint"'],"\n"; // Notice the column name is also made SQL-safe
}

// Assuming uuids.uuid is a UUID type column
foreach(['a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11',
'A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11',
'a0eebc999c0b4ef8bb6d6bb9bd380a11',
'{a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11}',
'Invalid Not-a-UUID',
'{a0eebc99-9c0b4ef8-bb6d6bb9-bd380a11}',
'a0ee-bc99-9c0b-4ef8-bb6d-6bb9-bd38-0a11',
] as
$uuid)
{
$tmp = ['uuid' => $uuid];
$vals = pg_convert($dbconn, 'uuids', ['uuid' => $uuid]);
echo
$vals['"uuid"'],"\n";
}

?>

All of the above data values will be "converted" - even the invalid ones - without complaint.
To Top