0

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
3
Contributors
3
Replies
4
Views
5 Years
Discussion Span
Last Post by Elandir
0

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 :)

Edited by cereal

0

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 ^^

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.