如果您的 `$nullAs` 是 `'\\N'`,那麼您應該在串接 `$rows` 的儲存格時照樣使用 `$nullAs`,但傳送到 `pgsqlCopyFromArray()` 時則需使用跳脫後的版本。此外,第五個參數 `$fields` 應該是 PostgreSQL 的 `COPY` 陳述式中 `column_names` 預留位置的有效 SQL 字串。
我提供了我的 `pgsqlCopyFromArray()` 智慧型包裝器,它會自動執行此操作。
<?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);
$value = addcslashes($value, "\0..\37");
return $value;
}, $fields);
$rows[] = implode($delimiter, $record) . "\n";
}
return $db->pgsqlCopyFromArray($tableName, $rows, $delimiter, addslashes($nullAs), implode(',', $fields));
}
?>