CakeFest 2024: The Official CakePHP Conference

PDO::pgsqlCopyFromArray

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

PDO::pgsqlCopyFromArrayPHP の配列から、データをテーブルにコピーする

説明

public PDO::pgsqlCopyFromArray(
    string $table_name,
    array $rows,
    string $delimiter = "\t",
    string $null_as = "\\\\N",
    string $fields = ?
): bool

rows 配列からデータをテーブル table_name にコピーします。 その際、delimiter をフィールドのデリミタ、そして fields のリストを使います。

パラメータ

table_name

テーブル名を含む文字列

rows

delimiter で区切られたフィールドの文字列の配列

delimiter

rows 配列で使われているデリミタ

null_as

どのように null 値を扱うかを指定します

fields

挿入するフィールドの一覧

戻り値

成功したら true を返します。 失敗した場合に false を返します

add a note

User Contributed Notes 1 note

up
2
Anonymous
8 years ago
If your $nullAs is '\\N', then you should use $nullAs as is in concatenation of cells of $rows, but send to pgsqlCopyFromArray() escaped version. Also fifth arg $fields should be a SQL-valid string for the column_names placeholder in COPY statement of PostgreSQL.

I provide my smart wrapper for pgsqlCopyFromArray() which do this automatically.

<?php
/**
*
* @param PDO $db
* @param string $tableName
* @param string[] $fields List of fields names.
* @param array[] $records Two-demension array of cells (array of rows).
* @return boolean
*/
function pgInsertByCopy (PDO $db, $tableName, array $fields, array $records) {
static
$delimiter = "\t", $nullAs = '\\N';

$rows = [];

foreach (
$records as $record) {
$record = array_map(
function (
$field) use( $record, $delimiter, $nullAs) {
$value = array_key_exists($field, $record) ? $record[$field] : null;

if (
is_null($value)) {
$value = $nullAs;
} elseif (
is_bool($value)) {
$value = $value ? 't' : 'f';
}

$value = str_replace($delimiter, ' ', $value);
// Convert multiline text to one line.
$value = addcslashes($value, "\0..\37");

return
$value;
},
$fields);
$rows[] = implode($delimiter, $record) . "\n";
}

return
$db->pgsqlCopyFromArray($tableName, $rows, $delimiter, addslashes($nullAs), implode(',', $fields));
}
?>
To Top