PHP SQL查询中的自定义标题

时间:2018-08-14 16:20:39

标签: php html postgresql

我有一个HTML表单,该表单在提交时调用php文档,该文档将表的值下载为csv文件。我的目标是利用select语句中的“ as”来实现该文档中的自定义列标题。例如,我想选择tableNAME.address并作为“站点位置”打印到csv。

以下是php示例以及postgres查询:

<?php
// show error messages
ini_set('error_reporting', E_ALL);
ini_set("display_errors", 1);


 if( !empty($_SERVER['REQUEST_METHOD']) && (strcasecmp($_SERVER['REQUEST_METHOD'], 'post')===0)  ) {
// Create connection
$conn = pg_connect("host=MYHOST port=ACCESS dbname=DBNAME user=USERNAME password=PWORD");

// Check connection
if (!$conn) {
echo "Did not connect.\n";
exit;
}
$result = pg_query($conn,
"
SELECT
tableNAME.address AS Address, 
tableNAME.city AS City, 
tableNAME.state_1 AS State, 
-- adds 0's if zip code is not long enough
  case length(tableNAME.zip)
    WHEN 5 THEN tableNAME.zip
    WHEN 4 THEN '0' || tableNAME.zip 
    WHEN 3 THEN '00' || tableNAME.zip
    END AS Zip
FROM 
  db.tableNAME
WHERE
  tableNAME.in_process = 'true' and
  tableNAME.shippiing = 'false' and
  tableNAME.soft_delete_id = '0' and
  tableNAME.status_1 <> 'Closed' and
  tableNAME.return_shipment = 'true'
ORDER BY
tableNAME.site_id asc;");

if (!$result) {
echo "Query failed.\n";
exit;
}

 $num_fields = pg_num_fields($result);
    $headers = array();

    for ($i = 0; $i < $num_fields; $i++) 
    {
        $headers[] = pg_field_name($result , $i);
    }

    $fp = fopen('php://output', 'w');
    if ($fp && $result)
    {
            header('Content-Type: text/csv');
            header('Content-Disposition: attachment; filename="ups_returns.csv"');
            header('Pragma: no-cache');
            header('Expires: 0');
            fputcsv($fp, $headers);

            while ($row = pg_fetch_row($result)) 
            {
                 fputcsv($fp, array_values($row));
            }
            die;

}
        exit('It works');
    }
?>

我已经尝试过在select as语句中使用撇号的各种变体。例如...

tableNAME.address as '""Site Location""'
tableNAME.address as 'Site Location'
tableNAME.address as '"Site Location"'

这些都不起作用。我相信我的代码行可能需要更改:

$headers = array();

但是,我不知道该怎么做才能使它工作。

谢谢

1 个答案:

答案 0 :(得分:0)

我找到了解决方法...而不是使用查询中的数据来确定标头,而是手动设置标头。

$headers = array('Site Location','City','State','Zip','Package Type','Weight','ShippingCode','TicketNumber','ReturnService','Return','BillTo','Attention','SiteID','PrintLabel');

//for ($i = 0; $i < $num_fields; $i++) 
//{
//    $headers[] = pg_field_name($result , $i);
//}