您好,我正在尝试构建一个 Web 界面,允许人们将 csv 文件的内容导入到 postgresql 数据库中。下面是我正在尝试执行的操作的 php 组件,但是当我运行时,我只是从我的 die 命令中得到“上传您的数据时出现问题:”但没有其他错误。
对于这个例子,我已经为 csv 文件硬编码了一个值,但目的是让用户指向他们机器或网络位置上的 csv 文件。
<?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);
}
?>
我很感激能提供的任何帮助。
最佳答案
COPY FROM file
必须由 super 用户帐户运行,此限制使其通常不适合网络使用
摘自 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.
但是 PHP 提供了对 COPY FROM stdin
的支持而没有这个限制。
php 文档中的这个示例展示了它是如何完成的:
$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\n");
pg_put_line($conn, "4\tgoodbye world\t7.11\n");
pg_put_line($conn, "\\.\n");
pg_end_copy($conn);
如果是文件,您需要使用 php 函数打开文件,然后使用 pg_put_line()
关于php - 通过网页中的php将CSV文件导入postgres,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18510954/