简体   繁体   中英

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";
}

?>

The issue is that you are not writing anything to the csv file before opening it.

Use this code

    $fp = fopen($filename, 'w');
    $result = mysql_query($query);

    $num_fields = mysql_num_fields($result);
    $headers = array();
    for ($i = 0; $i < $num_fields; $i++) {
        $headers[] = mysql_field_name($result , $i);
    }

    fputcsv($fp, $headers); 

    while($row = mysql_fetch_assoc($result)) {
        fputcsv($fp, $row); 
    }
    fclose($fp);


    header('Content-Type: text/csv');
    header( "Content-disposition: filename=".$filename);
    readfile($filename);

hey i have a code you can use it like this

    <?PHP

// Define  database connection variable dynamically
$DB_Server = "localhost";           //MySQL Server    
$DB_Username = "root";              //MySQL Username     
$DB_Password = "";                  //MySQL Password     
$DB_DBName = "test1";    //MySQL Database Name  
$DB_TBLName = "tabletest";          //MySQL Table Name   
$filename = "excelfilename";        //File Name
//create MySQL connection   
$sql = "Select * from csvtable";
$Connect = @mysqli_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:<br>" . mysqli_error() );
//select database   
$Db = @mysqli_select_db( $Connect,$DB_DBName) or die("Couldn't select database:<br>" . mysqli_error() );
//execute query 
$result = @mysqli_query( $Connect,$sql) or die("Couldn't execute query:<br>" . mysqli_error() );

function cleanData(&$str) 
{
    if ($str == 't')
        $str = 'TRUE';
    if ($str == 'f')
        $str = 'FALSE';
    if (preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
        $str = "'$str";
    }
    if (strstr($str, '"'))
        $str = '"' . str_replace('"', '""', $str) . '"';
}

// filename for download
$filename = "file_" . date('Ymd') . ".csv";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: text/csv;");
$out = fopen("php://output", 'w');
$flag = false;

while ($row = mysqli_fetch_assoc($result))
{
    if (!$flag) 
        {
        // display field/column names as first row 
        fputcsv($out, array_keys($row), ',', '"'); $flag = true; 
        }
    array_walk($row, 'cleanData');
    // insert data into database from here
    fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
exit;
//end
?>

Thanks to everyone for your suggestions, problem now solved, turned out to be a simple comma in the wrong place - "know_how_to_use," changed to " know_how_to_use" solved the problem. Thanks @Tintu C Raju for pointing me in the right direction

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM