gpt4 book ai didi

php - 使用 php 将 postgres 输出写入文件

转载 作者:行者123 更新时间:2023-11-29 13:32:34 26 4
gpt4 key购买 nike

我想将 postgres 查询的输出写入文件。我正在使用 php 连接到远程数据库并执行查询。这是示例代码。

$connection_id=pg_connect("host=localhost dbname=test user=test password=test");
$psql="select example from sample limit 180";
$result=pg_query($connection_id,$psql);

我已执行查询,但无法将其写入文件。我怎么做?

非常感谢您的帮助。

最佳答案

不能将查询结果直接写入文件。 pg_query返回的结果没有任何可以打印或写入文件的数据的字符串。它要么是错误状态 (false),要么是对为此查询保留的结果数据的某种“引用”。

如果 $result 不是 ==false 并且如果 PostgreSQL 可以找到任何行作为您查询的结果,那么您可以 fetch these rows .但这是一个额外的步骤。它不包含在 pg_query 中。为了检查找到了多少结果行,您可以使用函数 pg_num_rows .

然后您可以使用 pg_fetch_assoc 遍历结果集.这只是一个合适的功能。还有一些,例如pg_fetch_row

这是一些小的示例代码(快速且粗略,没有太多错误处理):

<?php 

// Set the output of this script to plain text
header("Content-Type: text/plain");

$conn = pg_connect("..."); // insert your data here
if (!$conn) die ("Couldn't connect.");

$result = pg_query($conn, "SELECT example FROM ..."); // TODO
// Check for error and check the number of rows found:
if ((!$result) || (pg_num_rows($result) < 1)) {
pg_close();
echo "Couldn't find any data for your query. Maybe the query is wrong (error) or there are no matching lines.";
exit;
}

// Line counter for screen output
$i = 1;

// Open file. (Important: Script must have write permission for the directory!)
$fileHandle = fopen("./myresults.txt", "w");

// Do this as long as you can find more result rows:
while ($row = pg_fetch_assoc($result)) {
// Write value to the output that is sent to the web browser client:
echo "Line " . $i . ": \"" . strip_tags($row['example']) . "\"\r\n";
// Write the same value as a new line into the opened file:
fwrite ($fileHandle, $row['example'] . "\r\n";
// Increase line number counter:
$i++;
}

// Close the file:
fclose ($fileHandle);

// Free the result / used memory:
pg_free_result($result);

pg_close();

?>

关于php - 使用 php 将 postgres 输出写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20156148/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com