在PHP中,可以使用以下兩種方法將數據庫表格輸出:
<?php
// 連接數據庫
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
// 查詢數據庫表格
$sql = "SELECT * FROM tablename";
$result = $conn->query($sql);
// 輸出表格
if ($result->num_rows > 0) {
echo "<table>";
echo "<tr><th>列1</th><th>列2</th></tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["列1"] . "</td><td>" . $row["列2"] . "</td></tr>";
}
echo "</table>";
} else {
echo "0 結果";
}
// 關閉數據庫連接
$conn->close();
?>
<?php
// 連接數據庫
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
// 查詢數據庫表格
$sql = "SELECT * FROM tablename";
$result = $conn->query($sql);
// 創建CSV文件
$filename = 'table.csv';
$fp = fopen($filename, 'w');
// 寫入表頭
$headers = array('列1', '列2');
fputcsv($fp, $headers);
// 寫入數據
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$row_data = array($row["列1"], $row["列2"]);
fputcsv($fp, $row_data);
}
}
// 關閉文件
fclose($fp);
// 下載CSV文件
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="' . $filename . '"');
readfile($filename);
// 刪除臨時文件
unlink($filename);
// 關閉數據庫連接
$conn->close();
?>
以上兩種方法可以根據需求選擇適合的方式將數據庫表格輸出。