PHP 8.3.4 Released!

pg_copy_from

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

pg_copy_from Insertar registros dentro de una tabla desde un array

Descripción

pg_copy_from(
    resource $connection,
    string $table_name,
    array $rows,
    string $delimiter = ?,
    string $null_as = ?
): bool

La función pg_copy_from() inserta registros dentro de una tabla desde el parámetro rows. Esta realiza internamente un comando SQL COPY FROM para insertar registros.

Parámetros

connection

Recurso de conexión a la base de datos PostgreSQL.

table_name

Nombre de la tabla en la cual se copiará lo que provenga de rows.

rows

Un array de datos a ser copiados dentro de table_name. Cada valor en el parámetro rows se convierte en una fila en table_name. Cada valor en el parámetro rows debe ser una cadena delimitada de los valores a insertar en cada campo. Los valores deben ser terminados con un salto de línea.

delimiter

Símbolo que serpara valores por cada campo en cada elemento del parámetro rows. El predeterminado es TAB.

null_as

Es como SQL NULL (anula) los valores que son representados en el parámetro rows. El predeterminado es \N ("\\N").

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de la función pg_copy_from()

<?php
$db
= pg_connect("dbname=publisher") or die("No se pudo conectar");

$rows = pg_copy_to($db, $table_name);

pg_query($db, "DELETE FROM $table_name");

pg_copy_from($db, $table_name, $rows);
?>

Ver también

add a note

User Contributed Notes 10 notes

up
7
karlo dot petravic at hotmail dot com
4 years ago
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);
?>
up
1
Rainer Perske
1 year ago
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.
up
1
smcbride at msn dot com
3 years ago
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.
up
1
Anonymous
14 years ago
see also: pg_put_line for a solution that does not require buffering of all the data to be copied,
up
0
Dave
10 years ago
Default is "\\\N" not "\\N" at least in php 5.4

pg_copy_from($db, $table_name, "\t", "\\\N")
up
0
vlad at php dot net
20 years ago
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)
up
-1
Dave
12 years ago
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");
?>
up
-1
kapouer_php at melix dot org
16 years ago
pg syntax is :
COPY test (cola, colb, colc) FROM stdin;
...

this function doesn't let you in which order the columns are !
up
-1
carl at thep.lu.se
21 years ago
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.
up
-9
Dave
13 years ago
Fix for "Copy command failed: ERROR: literal carriage return
found in data" or
"Copy command failed: ERROR: missing data for column
"message" CONTEXT: COPY message, line 1:"

<?php
$message
= "HEJ\rHEJ\nHEJ\r\nHEJ\n\rHEJ\tHELLO\\";

$message = addslashes($message);

$message = str_replace(
array(
"\n","\r","\t"),
array(
"\\n","\\r","\\t"),
$message);

$copy_message = "1\t". $message ."\t300";

pg_copy_from($db, "message", $copy_message);
?>
To Top