©
本文档使用
php.cn手册 发布
(PHP 5 >= 5.3.3)
PDO::pgsqlCopyFromArray — Copy data from PHP array into table
$table_name
, array $rows
[, string $delimiter
= '\t'
[, string $null_as
= "\\\\N"
[, string $fields
]]] )
Copies data from rows
array to table table_name
using delimiter
as fields delimiter and fields
list
table_name
String containing table name
rows
Array of strings with fields separated by delimiter
delimiter
Delimiter used in rows
array
null_as
How to interpret null values
fields
List of fields to insert
Returns TRUE
on success, 或者在失败时返回 FALSE
.
[#1] Anonymous [2015-09-09 16:05:41]
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
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));
}
?>