从PHP导出MSSQL查询到CSV文件

时间:2017-06-24 20:30:54

标签: php sql-server csv joomla html-table

我在joomla文章中使用了以下语法,我需要一种方法来添加一个php按钮(我知道语法或这个) - 并且按下按钮事件触发导出SQL查询结果(标题)和数据)到csv文件。这是我用来填充表格的语法。添加一个导出到.csv的函数是否容易修改?

<html>
<body>
    <form method="POST">
    </form>
</body>

<?php
$option = array();
$option['driver'] = 'mssql';
$option['host'] = 'IP Address';
$option['user'] = 'username';
$option['password'] = 'password';
$option['database'] = 'database';
$option['prefix'] = '';
$db = JDatabase::getInstance($option);
$query = $db->getQuery(true);
$query = "Select height, weight, userID, name from personelinfo;";
$db->setQuery($query);
$query = $db->loadObjectList();
if ($query) 
{
?>
<table border="1">
    <thead>
        <tr>
            <th>height </th>
            <th>weight </th>
            <th>userID </th>
            <th>name </th>
        </tr>
    </thead>
<?php
    foreach ($query as $res) 
    {
        print "<tr>";
        print "<td>" . $res->height . "</td>";
        print "<td>" . $res->weight . "</td>";
        print "<td>" . $res->userID . "</td>";
        print "<td>" . $res->name . "</td>";
        print "</tr>";
    }
} 
?>
</table>
</html>

1 个答案:

答案 0 :(得分:0)

您希望在PHP和HTML输出之间有更多的分离。当您想要输出其他格式(如CSV)时,这将很好地为您服务。在这里,我将数据库结果放在文件的顶部,并在完成任何输出之前将它们加载到一个数组中 - 理想情况下,这将在一个单独的文件中完成。

然后我们可以检查是否需要CSV输出。我已经更改了数据库代码以返回关联数组而不是对象,这使得将每行传递给fputcsv()变得微不足道。

注意我还使用alternative syntaxshort echo tags来减少PHP / HTML混合。这是一个很好的做法。最后,你的HTML一团糟;您在输出表格之前关闭了正文,并省略了<head><tbody>元素。

<?php
$option = array();
$option['driver']   = 'mssql';
$option['host']     = 'IP Address';
$option['user']     = 'username';
$option['password'] = 'password';
$option['database'] = 'database';
$option['prefix']   = '';
$db                 = JDatabase::getInstance($option);
$query              = "Select height, weight, userID, name from personelinfo;";

$db->setQuery($query);
$resultset = $db->loadAssocList();

if (!empty($_GET["csv"])) {
    $out = fopen("php://stdout");
    header("Content-Type: text/csv");
    foreach ($resultset as $res) {
        fputcsv($out, $res);
    }
    die;
}

?>
<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
</head>
<body>
<?php if(count($resultset):?>
<table border="1">
    <thead>
        <tr>
            <th>height </th>
            <th>weight </th>
            <th>userID </th>
            <th>name </th>
        </tr>
    </thead>
    <tbody>
<?php foreach($resultset as $res):?>
        <tr>
            <td><?= $res["height"] ?></td>
            <td><?= $res["weight"] ?></td>
            <td><?= $res["userID"] ?></td>
            <td><?= $res["name"] ?></td>
        </tr>
<?php endforeach;?>
    </tbody>
</table>
<form method="get">
    <button type="submit" name="csv" value="1">Export to CSV</button>
</form>
<?php endif;?>
</body>
</html>