pg_copy_from
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_copy_from — Вставляет записи из массива в таблицу
Описание
$connection
, string $table_name
, array $rows
[, string $delimiter
[, string $null_as
]] )
pg_copy_from() вставляет записи в таблицу из массива rows
.
В ходе выполнения вызывает SQL команду COPY FROM для вставки записей.
Список параметров
-
connection
-
Ресурс соединения с базой данных PostgreSQL.
-
table_name
-
Имя таблицы, в которую копируются значения из
rows
. -
rows
-
Массив (array) данных для копирования в
table_name
. Каждое значение вrows
становится строкой вtable_name
. Каждое значение массиваrows
должно быть строкой с разделителем, содержащей значения для вставки в каждое поле таблицы. Значения должны заканчиваться символом перевода строки. -
delimiter
-
Символ, отделяющий значения друг от друга в каждом элементе массива
rows
. По умолчанию TAB. -
null_as
-
Определяет, каким образом значения SQL NULL представлены в массиве
rows
. По умолчанию \N ("\\N").
Возвращаемые значения
Возвращает TRUE
в случае успешного завершения или FALSE
в случае возникновения ошибки.
Примеры
Пример #1 Пример использования pg_copy_from()
<?php
$db = pg_connect("dbname=publisher") or die("Не удается создать подключение");
$rows = pg_copy_to($db, $table_name);
pg_query($db, "DELETE FROM $table_name");
pg_copy_from($db, $table_name, $rows);
?>
- 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
Коментарии
Something needs to be said about the format of the array.
Judging by what I've seen, it's pretty much what you get
from loading a tab-separated file with file(). That is, the
lines are linefeed-terminated and there's no need to have
an extra line with "\.". On the other hand, when I try using this
command the connection to the server ends up in some odd
state and is then lost:
PHP Warning: U?S?o() query failed: server closed the connection unexpectedly
I think it might be safer to use the lower-level function
pg_put_line() for now.
By default NULL values are a backslash followed with capital N ("\\N").
Also, you can't insert entries with OIDs (I've added it to my TODO list though)
pg syntax is :
COPY test (cola, colb, colc) FROM stdin;
...
this function doesn't let you in which order the columns are !
see also: pg_put_line for a solution that does not require buffering of all the data to be copied,
As of postgresql 9.1 "standard_conforming_strings" is set to on
This will not work anymore
<?php
$copy_message = "1\t\\N\t300";
pg_copy_from($db, "message", $copy_message);
?>
result will be a "N" in that field. if the field allow text that is else it will fail to insert the post.
simple fix
<?php
$copy_message = "1\t\\NULL\t300";
pg_copy_from($db, "message", $copy_message, "\t","\\NULL");
?>
Default is "\\\N" not "\\N" at least in php 5.4
pg_copy_from($db, $table_name, "\t", "\\\N")
As table name you can also specify columns you want imported.
Will import all columns:
<?php
pg_copy_from($db, 'cpm.ics', $rows);
?>
Will import only specified columns:
<?php
pg_copy_from($db, 'cpm.ics (type, product, date, count, amount)', $rows);
?>
When using this function, don't get bit by the double quote (") vs. single quote (') differences. It is a small thing, but the error messaging is misleading. If you use a single quote, you will see the \t separated values all try to be inserted into the first field.
Small consideration, but will save someone who is working late and can't get these functions to work.
To solve the problem of how many backslashes to use for the parameters $separator and $null_as: The backslashes are interpreted twice, first by PHP and then by PostgreSQL. So write four backslashes to indicate one backslash in the input data. So both '\\\\N' and as "\\\\N" become NULL AS E'\\N' meaning the same as NULL AS '\N' in the internally used SQL statement.
The loaded input data must be backslash-escaped. According to the PostgreSQL documentation, you can use the following escape sequences:
\\ = Backslash (ASCII 92)
\b = Backspace (ASCII 8)
\t = Tab (ASCII 9)
\n = Newline (ASCII 10)
\v = Vertical tab (ASCII 11)
\f = Form feed (ASCII 12)
\r = Carriage return (ASCII 13)
\000 (Backslash followed by one to three octal digits) = the byte with that numeric code
\x00 (Backslash x followed by one or two hex digits) = the byte with that numeric code
With the default setting, a data field containing only \N (one non-escaped backslash and an N) indicates a NULL value. This default value \N has been chosen because it does not collide with properly encoded data.