Exporting to CSV from MySQL via PHP in FireFox
Posted
by typoknig
on Stack Overflow
See other posts from Stack Overflow
or by typoknig
Published on 2010-05-03T19:33:32Z
Indexed on
2010/05/03
19:38 UTC
Read the original article
Hit count: 371
Hi all, I am pulling some info from a database with the following code:
<input type="button" value="Export to Excel" onClick="window.navigate('breakfast_service.php?action=export')">
Here is the code for that action.
<?php
if ($_GET['action'] == 'export')
{
// Get the registration data
$user = 'root';
$pass = 'billiards';
$server = 'localhost';
$link = mysql_connect($server, $user, $pass);
if (!$link)
{
die('Could not connect to database!' . mysql_error());
}
mysql_select_db('breakfast', $link);
$query = "SELECT * FROM registration";
$result = mysql_query($query);
mysql_close($link);
// format into CSV
$contents = "id, school_id, first_name, last_name, email, attending, created_on\n";
$num = mysql_num_rows($result);
for ($i = 0; $i < $num; $i++)
{
$row = mysql_fetch_array($result);
$id = $row['id'];
$school_id = $row['school_id'];
$fname = $row['first_name'];
$lname = $row['last_name'];
$email = $row['email'];
$attending = ($row['attending'] == 0) ? 'No' : 'Yes';
$date = $row['created_on'];
$contents = $contents . "$id, $school_id, $fname, $lname, $email, $attending, $date\n";
}
// return as excel file
$filename = "export.csv";
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename='.$filename);
echo $contents;
}
?>
This combination of code works excellent in IE, but fails to do create/download a file in Firefox or Chrome. Why?
© Stack Overflow or respective owner