pg_convert
(PHP 4 >= 4.3.0, PHP 5)
pg_convert — Convert associative array values into suitable for SQL statement
Description
$connection
, string $table_name
, array $assoc_array
[, int $options
= 0
] )
pg_convert() checks and converts the values in
assoc_array
into suitable values for use in an SQL
statement. Precondition for pg_convert() is the
existence of a table table_name
which has at least
as many columns as assoc_array
has elements. The
fieldnames in table_name
must match the indices in
assoc_array
and the corresponding datatypes must be
compatible. Returns an array with the converted values on success, FALSE
otherwise.
Note:
Since PHP 5.6.0, it accepts boolean values. It converted to PostgreSQL boolean. String representations of boolean value is also supported.
NULL
is converted to PostgreSQL NULL.Prior to PHP 5.6.0, if there are boolean fields in
table_name
don't use the constantTRUE
inassoc_array
. It will be converted to the string 'TRUE' which is no valid entry for boolean fields in PostgreSQL. Use one of t, true, 1, y, yes instead.
Parameters
-
connection
-
PostgreSQL database connection resource.
-
table_name
-
Name of the table against which to convert types.
-
assoc_array
-
Data to be converted.
-
options
-
Any number of
PGSQL_CONV_IGNORE_DEFAULT
,PGSQL_CONV_FORCE_NULL
orPGSQL_CONV_IGNORE_NOT_NULL
, combined.
Return Values
An array of converted values, or FALSE
on error.
Examples
Example #1 pg_convert() example
<?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);
?>
Changelog
Version | Description |
---|---|
5.6.0 | No longer experimental. Boolean/NULL data types are supported. Unknown/unsupported data types are escaped without validation. pg_convert() could be used with any data types. |
See Also
- pg_meta_data() - Get meta data for table
- pg_insert() - Insert array into table
- pg_select() - Select records
- pg_update() - Update table
- pg_delete() - Deletes records
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения для работы с базами данных
- Расширения для работы с базами данных отдельных производителей
- PostgreSQL
- pg_affected_rows
- pg_cancel_query
- pg_client_encoding
- pg_close
- pg_connect_poll
- pg_connect
- pg_connection_busy
- pg_connection_reset
- pg_connection_status
- pg_consume_input
- pg_convert
- pg_copy_from
- pg_copy_to
- pg_dbname
- pg_delete
- pg_end_copy
- pg_escape_bytea
- pg_escape_identifier
- pg_escape_literal
- pg_escape_string
- pg_execute
- pg_fetch_all_columns
- pg_fetch_all
- pg_fetch_array
- pg_fetch_assoc
- pg_fetch_object
- pg_fetch_result
- pg_fetch_row
- pg_field_is_null
- pg_field_name
- pg_field_num
- pg_field_prtlen
- pg_field_size
- pg_field_table
- pg_field_type_oid
- pg_field_type
- pg_flush
- pg_free_result
- pg_get_notify
- pg_get_pid
- pg_get_result
- pg_host
- pg_insert
- pg_last_error
- pg_last_notice
- pg_last_oid
- pg_lo_close
- pg_lo_create
- pg_lo_export
- pg_lo_import
- pg_lo_open
- pg_lo_read_all
- pg_lo_read
- pg_lo_seek
- pg_lo_tell
- pg_lo_truncate
- pg_lo_unlink
- pg_lo_write
- pg_meta_data
- pg_num_fields
- pg_num_rows
- pg_options
- pg_parameter_status
- pg_pconnect
- pg_ping
- pg_port
- pg_prepare
- pg_put_line
- pg_query_params
- pg_query
- pg_result_error_field
- pg_result_error
- pg_result_seek
- pg_result_status
- pg_select
- pg_send_execute
- pg_send_prepare
- pg_send_query_params
- pg_send_query
- pg_set_client_encoding
- pg_set_error_verbosity
- pg_socket
- pg_trace
- pg_transaction_status
- pg_tty
- pg_unescape_bytea
- pg_untrace
- pg_update
- pg_version
Коментарии
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.
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.
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]*)?[ ...
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.
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.