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

标签 php file postgresql

我想将 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/

相关文章:

php - 在 Laravel 中将依赖参数传递给 App::make() 或 App::makeWith()

c++ - 使用 stat 列出文件及其信息

javascript - 从文件中读取并查找特定行

windows - 二进制将所有文件与指定目录(和子目录)中的所有文件进行比较

postgresql - 在表上添加触发器时出现 PSQLException 和锁定问题

sql - 在 postgres 中拆分列值

php - SOAP - 加载本地 WSDL 文件

javascript - 将数组从页面模板传递到 WordPress 主题文件夹中的另一个 php 文件

没有额外行的 PHP 引用数组项

sql - 当年的第一天