使用 php 执行 Postgres 查询并使结果可供下载

发布于 2024-12-12 00:09:06 字数 2410 浏览 0 评论 0原文

我得到一个查询,在一个场景中我执行查询,它以包含数据和标题等的表格格式显示结果...我想创建的第二个场景是一个直接下载链接,它将执行查询并放置结果转换为 .csv 文件以便在 Excel 中保存或打开。我已经有了显示代码,但我想知道如何为用户下载它。

这是执行和显示的一些代码。

    <?php
    $month = $_POST['mydate'];
    $monthfrm = date("Y-m-d", strtotime($month));
    $monthhd = date("F", strtotime($month));
    $monthto = date("Y-m-d", strtotime("$monthfrm . +1 month"));
    $date = date("F j,Y");
    if ($_POST['credsubmit']) {
       print('<head>');
       print('<link href="helper.css" media="screen" rel="stylesheet" type="text/css" />');
       print('<link href="dropdown.css" media="screen" rel="stylesheet" type="text/css" />');
       print('<link href="default.css" media="screen" rel="stylesheet" type="text/css" />');
    // Connecting, selecting database
       $dbconn = pg_connect("yeah we all know what goes here");
         if (!$dbconn) {
          die('Could not connect: ' . pg_last_error());
          }// Performing SQL query
     $query = "
       SELECT cm.\"ID\",a.\"ID\" as \"DDI\",cm.\"Date\",c.\"Amount\",ct.\"Name\" as \"Name\",cm.\"Comments\" as \"Comments\"
       FROM \"BIL_CreditMemo\" cm
       LEFT JOIN \"BIL_Credit\" c ON (c.\"ID\" = cm.\"BIL_CreditID\")
       LEFT JOIN \"ACT_Account\" a ON (c.\"ACT_AccountID\" = a.\"ID\")
       LEFT JOIN \"BIL_val_CreditMemoReason\" ct ON (ct.\"ID\" = cm.\"BIL_val_CreditMemoReasonID\")
       WHERE cm.\"Date\" >= '$monthfrm' AND cm.\"Date\" < '$monthto';
       ";
       $result = pg_query($query) or die('Query failed: ' . pg_last_error());
       // Printing results in HTML
       echo "<h2 align=center style=margin-top:20>Credit Memo Report for: $monthhd</h2>";
       echo "<table align=center width=60%>\n";
       print('<tr class="trstyle"><td>ID</td><td>DDI</td><td>Date</td><td>Amount</td><td>Name</td><td>Comments</td></tr>');
       while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
       echo "\t<tr>\n";
         foreach ($line as $col_value) {
           echo "\t\t<td>$col_value</td>\n";
         }
       echo "\t</tr>\n";
      }
      echo "</table>\n";// Free resultset
      pg_free_result($result);// Closing connection
      pg_close($dbconn);
      }
      ?>

这就是我到目前为止得到的结果并希望将结果直接下载到 csv 文件吗?非常感谢任何帮助。

I got a Query that in one scenario I execute the query and it displays the results in a table format with data and headers etc... The second scenario I want to creat is a direct download link that will execute the query and put the results into a .csv file for saving or opening in Excel. I have the code for the display already but I am wondering how to make it download for the user.

Here is a tidbit of code for the execute and display.

    <?php
    $month = $_POST['mydate'];
    $monthfrm = date("Y-m-d", strtotime($month));
    $monthhd = date("F", strtotime($month));
    $monthto = date("Y-m-d", strtotime("$monthfrm . +1 month"));
    $date = date("F j,Y");
    if ($_POST['credsubmit']) {
       print('<head>');
       print('<link href="helper.css" media="screen" rel="stylesheet" type="text/css" />');
       print('<link href="dropdown.css" media="screen" rel="stylesheet" type="text/css" />');
       print('<link href="default.css" media="screen" rel="stylesheet" type="text/css" />');
    // Connecting, selecting database
       $dbconn = pg_connect("yeah we all know what goes here");
         if (!$dbconn) {
          die('Could not connect: ' . pg_last_error());
          }// Performing SQL query
     $query = "
       SELECT cm.\"ID\",a.\"ID\" as \"DDI\",cm.\"Date\",c.\"Amount\",ct.\"Name\" as \"Name\",cm.\"Comments\" as \"Comments\"
       FROM \"BIL_CreditMemo\" cm
       LEFT JOIN \"BIL_Credit\" c ON (c.\"ID\" = cm.\"BIL_CreditID\")
       LEFT JOIN \"ACT_Account\" a ON (c.\"ACT_AccountID\" = a.\"ID\")
       LEFT JOIN \"BIL_val_CreditMemoReason\" ct ON (ct.\"ID\" = cm.\"BIL_val_CreditMemoReasonID\")
       WHERE cm.\"Date\" >= '$monthfrm' AND cm.\"Date\" < '$monthto';
       ";
       $result = pg_query($query) or die('Query failed: ' . pg_last_error());
       // Printing results in HTML
       echo "<h2 align=center style=margin-top:20>Credit Memo Report for: $monthhd</h2>";
       echo "<table align=center width=60%>\n";
       print('<tr class="trstyle"><td>ID</td><td>DDI</td><td>Date</td><td>Amount</td><td>Name</td><td>Comments</td></tr>');
       while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
       echo "\t<tr>\n";
         foreach ($line as $col_value) {
           echo "\t\t<td>$col_value</td>\n";
         }
       echo "\t</tr>\n";
      }
      echo "</table>\n";// Free resultset
      pg_free_result($result);// Closing connection
      pg_close($dbconn);
      }
      ?>

So that is what I got so far and want to make the results a direct download to a csv file? Any help is greatly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

就此别过 2024-12-19 00:09:06

您需要设置一些 HTTP 标头,然后只需回显 CSV 数据即可。例如,

<?php
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=test.csv");
header("Pragma: no-cache");
header("Expires: 0");


echo "Name,Favourite Colour\n";
echo "Phil,Blue\n";
?>

请注意,如果您专门针对 Excel,则可以使用一些库来创建 .xls 文件;我非常喜欢 PHPExcel

You need to set a few HTTP headers, then you just echo out CSV data. For example,

<?php
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=test.csv");
header("Pragma: no-cache");
header("Expires: 0");


echo "Name,Favourite Colour\n";
echo "Phil,Blue\n";
?>

Note that if you're specifically targeting Excel, then there are libraries that will allow you to create .xls files; I quite like PHPExcel

寂寞清仓 2024-12-19 00:09:06
  1. 使用 header() 函数告诉浏览器输出将是一个八位字节溪流。
  2. 使用 fputcsv() 将查询结果以 CSV 格式写入临时文件。
  3. 使用 readfile() 发送文件内容。

或者,有一种方法可以让 fputcsv() 将其数据直接写入 STDOUT,但这需要一些技巧,但它可以让您跳过使用临时文件。无论哪种方式,我都会阅读 readfile() 的示例,因为它将帮助您设置标头以启动您正在寻找的“文件下载”。

  1. Use the header() function to tell the browser that the output will be an octet stream.
  2. Use fputcsv() to write the results of the query to a temporary file in CSV format.
  3. Send the content of the file using readfile().

Alternately, there is a way to make fputcsv() write its data directly to STDOUT, but it'll take a little bit of finagling, but it'll let you skip using a temp file. Either way, I'd read the examples for readfile() as it'll help you set up the headers to initiate the "file download" that you're looking for.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文