Export MySQL data to .csv using PHP

纵饮孤独 提交于 2019-12-04 12:10:20

Try this :

$rows = mysql_query("SELECT `name`, `gender` FROM TABLE");

while ($row = mysql_fetch_assoc($rows)) {

    if($row['gender'] == 1) {
        $row['gender'] = 'Male'; 
    } else {
        $row['gender'] = 'Female'; 
    }

    // Or ternary condition
    // $row['gender'] = ($row['gender'] == 1 ? 'Male' : 'Female');

    fputcsv($output, $row);
}
<?php

    $db_record = 'yourRecod';
    // optional where query
    $where = 'WHERE 1 ORDER BY 1';
    // filename for export
    $csv_fileName = 'db_export_'.$db_record.'_'.date('Y-m-d').'.csv';

    // database variables
    $hostname = "localhost";
    $user = "yourUserName";
    $password = "yourPassword";
    $database = "yourDataBase";

    // Database connecten voor alle services
    mysql_connect($hostname, $user, $password)
    or die('Could not connect: ' . mysql_error());

    mysql_select_db($database)
    or die ('Could not select database ' . mysql_error());

    $csv_export = '';

    $query = mysql_query("SELECT * FROM ".$db_record." ".$where);
    $field = mysql_num_fields($query);

    // create line with field names
    for($i = 0; $i < $field; $i++) {
      $csv_export.= mysql_field_name($query,$i).';';
    }
    $csv_export.= '';
    while($row = mysql_fetch_array($query)) {
      // create line with field values
      for($i = 0; $i < $field; $i++) {
        $csv_export.= '"'.$row[mysql_field_name($query,$i)].'";';
      } 
      $csv_export.= ''; 
    }

    // Export the data and prompt a csv file for download
    header("Content-type: text/x-csv");
    header("Content-Disposition: attachment; filename=".$csv_fileName."");
    echo($csv_export);
?>

i give you full sample code which i am using to Export MySql data to .CSV using PHP

John Ezell

Use the IF statement in your SQL to minimize PHP logic:

SELECT `name`, IF(gender=1,'Male','Female') as 'gender' FROM TABLE
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!