<?php
// Database connection (Procedural MySQLi)
$conn = mysqli_connect("localhost", "username", "password", "database_name");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Query to fetch data (adjust as needed)
$query = "SELECT * FROM users"; // Change this query as needed
$result = mysqli_query($conn, $query);
// Set headers to trigger Excel file download
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=export.xls");
header("Pragma: no-cache");
header("Expires: 0");
// Start outputting the table in HTML format (Excel will interpret it as an Excel file)
echo "<table border='1'>";
// Get the column names dynamically
$fields = mysqli_fetch_fields($result);
// Print the table headers
echo "<tr>";
foreach ($fields as $field) {
echo "<th>" . htmlspecialchars($field->name) . "</th>";
}
echo "</tr>";
// Fetch and output the rows
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
foreach ($row as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>";
}
// Close the table
echo "</table>";
// Free result and close the connection
mysqli_free_result($result);
mysqli_close($conn);
?>
0 Comments