Skip to content
PHP Logo

What is the purpose of using PDO::pgsqlCopyToArray() in PHP for migrating data between databases?

When migrating data between PostgreSQL databases in PHP, using PDO::pgsqlCopyToArray() can efficiently transfer large datasets by copying data from one table to another. This method leverages PostgreSQL's COPY TO command to export data in a tab-separated format, which is then imported into the target database using the COPY FROM command. This process is faster and more efficient than traditional INSERT statements, especially for large datasets.

php
// Connect to the source and target databases
$sourceDb = new PDO('pgsql:host=source_host;dbname=source_db', 'username', 'password');
$targetDb = new PDO('pgsql:host=target_host;dbname=target_db', 'username', 'password');

// Copy data from source table to target table
$sourceTable = 'source_table';
$targetTable = 'target_table';

$copyData = $sourceDb->pgsqlCopyToArray("COPY $sourceTable TO STDOUT", "\t");
$targetDb->pgsqlCopyFromArray("COPY $targetTable FROM STDIN", $copyData, "\t");

echo "Data migration completed successfully.";