Link to home
Start Free TrialLog in
Avatar of BR
BRFlag for Türkiye

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?
Avatar of Tomas Helgi Johannsson
Tomas Helgi Johannsson
Flag of Iceland image

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
Avatar of 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
Avatar of Tomas Helgi Johannsson
Tomas Helgi Johannsson
Flag of Iceland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of 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
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
Avatar of BR

ASKER

Thank you so much Tomas Helgi Johannsson