Export MySQL data to .csv using PHP
Asked Answered
S

3

3

I'm exporting data to a .csv file and it's working perfectly but I have one small issue. I fetch name and gender from a table but for gender I save id in my database (i.e., 1 = Male, 2 = Female). My below code gives me id for gender, how can I fix it? Return 1 for Male and 2 for Female:

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

while ($row = mysql_fetch_assoc($rows)) {
    fputcsv($output, $row);
}
Scorpius answered 7/3, 2014 at 13:52 Comment(1)
Apparently not, luckily for them someone will always post a solution anyway.Jeannajeanne
P
6

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);
}
Pritchard answered 7/3, 2014 at 13:55 Comment(1)
Ternary condition seems nicely to me @Pritchard ;)Gomer
B
2
<?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

Byelorussian answered 7/3, 2014 at 14:3 Comment(1)
This dosnt give me linebreaks for each new row :-(Danny
I
2

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

SELECT `name`, IF(gender=1,'Male','Female') as 'gender' FROM TABLE
Intermittent answered 12/8, 2014 at 20:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.