How can the pg_fetch function be used as an alternative to the PostgreSQL COPY command for exporting data in PHP?
When exporting data from a PostgreSQL database in PHP, the pg_fetch function can be used as an alternative to the COPY command. By querying the data using pg_fetch and then writing it to a file, you can achieve a similar result to the COPY command. This method allows for more flexibility and control over the exported data.
<?php
// Connect to the database
$conn = pg_connect("host=localhost dbname=mydb user=myuser password=mypassword");
// Query the data
$result = pg_query($conn, "SELECT * FROM mytable");
// Open a file for writing
$file = fopen("exported_data.csv", "w");
// Loop through the results and write them to the file
while ($row = pg_fetch_assoc($result)) {
fputcsv($file, $row);
}
// Close the file and database connection
fclose($file);
pg_close($conn);
?>