Exporting to CSV from MySQL via PHP

I am trying to bug fix a PHP script that should export values from a MySQL database to a CSV file.

The PHP file is returning a blank CSV file & I can’t figure out why & I’ve been stuck on this for quite a while, so any help would be much apprwciated.

Code below:

<?
include('../../../inc/config.php');
$period = $_GET['pid'];

$psql = "SELECT month, year FROM survey_period WHERE sid = " . $period;
$pres = mysql_query($psql, $dcon);
$prow = mysql_fetch_array($pres);
$pmonth = $prow['month'];
$pyear = $prow['year'];

$query="SELECT
    sid,
    date,
    stove_id,
    name,
    gender,
    marital_status,
    occupation_of_household,
    cz_stove AS km_stove,
    happy_with_cz_stove AS happy_with_km_stove,
    cz_stove_in_use AS km_stove_in_use,
    know_how_to_use,
    FROM survey_usage WHERE period = " . $_GET['pid'];
$result = mysql_query($query, $dcon);
  //header('Content-Disposition: attachment;filename=export.csv');
$filename = 'usage-'.$pid.'-'.$pmonth.'-'.$pyear;
header('Content-Type: text/csv');
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
$row = mysql_fetch_assoc($result);
if ($row) {
echocsv(array($title));
echo "\r\n";
    echocsv(array_keys($row));
}
while ($row) {
    echocsv($row);
    $row = mysql_fetch_assoc($result);
}
function echocsv($fields)
{
    $separator = '';
    foreach ($fields as $field) {
        if (preg_match('/\\r|\\n|,|"/', $field)) {
            $field = '"' . str_replace('"', '""', $field) . '"';
        }
        echo $separator . $field;
        $separator = ',';
    }
    echo "\r\n";
}

?>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s