Hello there!
I've been trying to import data from csv file to remote postgre database with no luck. Locally i can do it with simple COPY query, but that only works because i'm superuser. \COPY command also works when i run it in psql. So the question is: how can i do it in PHP? Is there function that runs psql commands?
Query example:

COPY table1(field1, field2, field3)
FROM '/filepath/data.csv'
WITH DELIMITER ';'
CSV HEADER;


\copy table1(field1, field2, field3)
FROM '/filepath/data.csv'
WITH DELIMITER ';'
CSV HEADER

Recommended Answers

All 3 Replies

You can use explode(), basically: explode(';', 'data;goes;here'). An example:

<?php
  $f = file_get_contents('/filepath/data.csv');  
  $f = array_filter(array_map('trim',(explode(';',$f))));
  print_r($f);

  # in addition you can run array_chunk() this will split the array, it can be helpful in loops
  print_r(array_chunk($f,3));
?>

file_get_contents() is used to read data from csv file, array_filter() is used to remove empty entries from the resulting array, array_map is used to use trim() function, so you can remove white spaces at the end of each string.

Once you have the array just run a query to insert data. Hope it's useful. Bye :)

pg_query() wont work because \copy is psql command. Guess i'll have to look into reading the csv file and then executing insert into query.

Thank You for quick replys and an idea i can use ^^

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.