Export MySQL data to .csv using PHP

Arif picture Arif · Mar 7, 2014 · Viewed 15.2k times · Source

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

Answer

ncrocfer picture ncrocfer · Mar 7, 2014

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