[英]Export MSSQL Query To CSV File From PHP
我在我的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>
您希望在PHP和HTML輸出之間有更多的分離。 當您想要輸出其他格式(如CSV)時,這將很好地為您服務。 在這里,我獲取文件頂部的數據庫結果,並在完成任何輸出之前將它們加載到數組中 - 理想情況下,這將在單獨的文件中完成。
然后我們可以檢查是否需要CSV輸出。 我已經更改了數據庫代碼以返回關聯數組而不是對象,這使得將每行傳遞給fputcsv()
變得微不足道。
注意我還使用了替代語法和短回聲標記來減少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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.