1

Possible Duplicate:
Create a CSV File for a user in PHP

I am looking for a solution to create a CSV download link from a mysql query for my little project.

Basically the download link will be in this format :

http://localhost/vnodes/generateExcel.php?fromDate=2012-07-23&toDate=2012-07-24&location=1

in which my generateExcel.php will contain this :

<?php

$fromDate = $_GET['fromDate'];
$toDate = $_GET['toDate'];
$location = $_GET['location'];

include "connect.php";
$connect = mysql_connect($dbhost, $dbusername, $dbpassword) or die(mysql_error()); 
mysql_select_db($dbname) or die(mysql_error());
$query = mysql_query("SELECT * FROM `nodes` WHERE `dateIn` BETWEEN '$fromDate' AND '$toDate' AND partLocation = '$location' ORDER BY `dateIn` ASC") or die(mysql_error());

header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=report.csv");
header("Pragma: no-cache");
header("Expires: 0");

while($result = mysql_fetch_array($query)) {
    echo $result['dateIn'].",".$result['partNumber'].",".$result['serialNumber'].",".$result['4serialNumber'].",".$result['status'].",".$result['operator']."\n";
}
?>

The thing I do not know is how to make a CSV out of the $query output and trigger a download.

Thank you for any help!

Community
  • 1
  • 1
JudeJitsu
  • 730
  • 1
  • 10
  • 17
  • 1
    Please, don't use `mysql_*` functions for new code. They are no longer maintained and the community has begun the [deprecation process](http://goo.gl/KJveJ). See the [**red box**](http://goo.gl/GPmFd)? Instead you should learn about [prepared statements](http://goo.gl/vn8zQ) and use either [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli). If you can't decide, [this article](http://goo.gl/3gqF9) will help to choose. If you care to learn, [here is good PDO tutorial](http://goo.gl/vFWnC). – Manse Jul 24 '12 at 11:42
  • Thanks @ManseUK. Will try to read on PDO and MySQLi. About the possible duplicate, yeah it might be the case, but I do not really understand what it meant. Basically I want to create a CSV out of the `$results` array, which I do not know how to do. – JudeJitsu Jul 24 '12 at 11:44
  • I have tried implementing the link from the first comment, edited my post, but the downloaded CSV file contains "SCREAM" errors. What am I doing wrong? – JudeJitsu Jul 24 '12 at 11:54
  • 1
    are you echoing anything before the `header` function call ? – Manse Jul 24 '12 at 11:57
  • @ManseUK, figured it out thank you so much! – JudeJitsu Jul 25 '12 at 00:40

1 Answers1

2

Change the content type to text/csv

header("Content-type: text/csv");

And move the header() calls to the top of the script.

And use PDO or mysqli as suggested in the comments.

Ed Manet
  • 3,118
  • 3
  • 20
  • 23