douguwo2275 2013-08-29 12:24
浏览 46

通过网页上的php将CSV文件导入postgres

Hi I'm trying to build a web interface that will allow people to import the contents of a csv file into a postgresql database. Below is the php component of what I'm trying to do, however when I run I just get "There was a problem uploading your data:" from my die command but with no other error.

For this example, I have hardcoded a value for the csv file, however the intent is for the user to point at a csv file on their machine or network location.

<?php

if ($_POST['submit']) {
// attempt a connection
$dbh = pg_connect("host=localhost dbname=blah user=user password=pass123");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// execute query
$sql = "COPY personaldetails(name, email, postaladdress, phone, username, password) FROM '../Test/Book1.csv' WITH DELIMITER ',' CSV";

$result = pg_query($dbh, $sql);
if (!$result) {
die("There was a problem uploading you data: " . pg_last_error());
}

echo "Data successfully inserted!";

// free memory
pg_free_result($result);

// close connection
pg_close($dbh);
}   

?>

I appreciate any help that can be offered.

  • 写回答

1条回答 默认 最新

  • drgzmmy6379 2013-08-29 12:55
    关注

    COPY FROM file must be run by a superuser account and this restriction makes it generally unsuitable for web usage

    Excerpt from the documentation:

    COPY naming a file is only allowed to database superusers, since it allows reading or writing any file that the server has privileges to access.

    But PHP provides support for COPY FROM stdin which does not have this restriction. This example from php documentation shows how it's done:

      $conn = pg_pconnect("dbname=foo");
      pg_query($conn, "create table bar (a int4, b char(16), d float8)");
      pg_query($conn, "copy bar from stdin");
      pg_put_line($conn, "3\thello world\t4.5
    ");
      pg_put_line($conn, "4\tgoodbye world\t7.11
    ");
      pg_put_line($conn, "\\.
    ");
      pg_end_copy($conn);
    

    In the case of a file, you'll need to open the file with php functions and feed it line by line to the postgres connection with pg_put_line()

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!