简体   繁体   中英

How to import a csv with copy function using php

I need to import a csv file into my database. I first wrote the function in SQL but now I need to do it in php, I don't want to change my entire code so I just figured I could execute the SQL query with php but I get an error.

    $query="COPY bet_import FROM $1 DELIMITER ',' CSV HEADER";
    $result = pg_prepare($dbh, "", $query);
    $result = pg_execute($dbh, "",array('bet.csv'));

I get the error:

Error: Warning: pg_prepare(): Query failed: ERROR: syntax error at or near "$1" LINE 1: COPY bet_import FROM $1 DELIMITER ',' CSV HEADER

You cannot bind identifiers (table name, field name) in the prepare statement. You need to add that into the query. If you are dynamically getting it you can escape it or sanitize it before you run the query. In your query the file path is an identifier.

$filePath = 'bet.csv';
$query="COPY bet_import FROM '$filePath' DELIMITER ',' CSV HEADER";
$result = pg_prepare($dbh, "", $query);
$result = pg_execute($dbh, "",array());

You have to pass the filename in the query itself. This query will run on the postgresql so you need to specify the absolute path of the file.. If this file is placed in same code as your php code then also you need to specify the absolute path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM