php-mysqlHow to export data from MySQL to Excel using PHP?
Exporting data from MySQL to Excel using PHP is a simple process. The following example code will export the data from a MySQL table to an Excel file:
<?php
$connect = mysqli_connect("localhost", "username", "password", "database_name");
$output = '';
$sql = "SELECT * FROM table_name";
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0)
{
$output .= '
<table class="table" bordered="1">
<tr>
<th>Name</th>
<th>Address</th>
<th>City</th>
</tr>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["name"].'</td>
<td>'.$row["address"].'</td>
<td>'.$row["city"].'</td>
</tr>
';
}
$output .= '</table>';
header('Content-Type: application/xls');
header('Content-Disposition: attachment; filename=download.xls');
echo $output;
}
?>
This code will output an Excel file with the data from the MySQL table.
The code consists of the following parts:
- Connecting to the MySQL database using
mysqli_connect()
- Creating an SQL query to select the data from the table using
$sql
- Executing the query using
mysqli_query()
- Looping through the results using
mysqli_fetch_array()
- Creating an HTML table with the data using
$output
- Setting the headers for the Excel file using
header()
- Outputting the Excel file using
echo
Helpful links
More of Php Mysql
- How to use a variable in a MySQL query using PHP?
- How to use utf8mb4_unicode_ci in MySQL with PHP?
- How to create an SSL connection to MySQL using PHP?
- How to update to null value in MySQL using PHP?
- How to set a timeout for MySQL query in PHP?
- How to get the first row of a result in MySQL using PHP?
- How to use a MySQL union in PHP?
- How to generate a UUID in MySQL using PHP?
- How to hash a password in PHP and MySQL?
- How to get the version of MySQL using PHP?
See more codes...