Avatar of BR
BR
Flag for Turkey asked on

how to export to excel from mysql database using php

Dear Experts,
I use PHP 7 and mysql database.
I searched on the web how to export data to excel , I found many old codes with mysql_connect...
I need to use mysqli not mysql

Do you recomend me some working code?
PHPMySQL Server

Avatar of undefined
Last Comment
BR

8/22/2022 - Mon
Tomas Helgi Johannsson

Hi!

The simplest way to export data to excel is to export to csv using mysqli like this

<?php 
$con = new mysqli($host, $user, $password, $database);
 
// Check connection
if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
}
$result = mysqli_query($con, 'SELECT * FROM table');
if (mysqli_num_rows($result) > 0) {
$fp = fopen('file.csv', 'w');
while ($row = mysqli_fetch_assoc($result)) {
  fputcsv($fp, $row);
}
fclose($fp);
}
?>

Open in new window


Regards,
   Tomas Helgi
BR

ASKER
Dear Thomas, Thank you, but I already have a wonderful export as csv code ( thanks to Ray Paseur )

However I need to export as excel ( not come seperated values )
Do you have code for that? Thank you
ASKER CERTIFIED SOLUTION
Tomas Helgi Johannsson

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
BR

ASKER
Dear Tomas Helgi, thank you for the wonderful code. One more thing I'd like to ask you about this code.

the letters like Ö, İ, Ş , Ğ is not shown properly on the Excel. Instead of this letters, it shows ? ( question mark ) on the excel table?

How can I correct this? Thank you
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
Tomas Helgi Johannsson

Hi!

For that you will probably include correct language in the header of the PHP/HTTP response.
header("Content-Language: <your language>")

Open in new window


See further here on what other headers you could use.
http://php.net/manual/en/function.header.php
http://www.jonasjohn.de/snippets/php/headers.htm

Regards,
     Tomas Helgi
BR

ASKER
Thank you so much Tomas Helgi Johannsson