Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

save mysql table as csv modifying file some of the cell data in php

Tags:

php

mysql

csv

I need to download a mysql table as a csv file. Okay, Now thats no big thing. But I need to modify the cell contents when I download it. For eg. In the table male, female and others are denoted as 1 2 and 3 respectively. But the downloaded excel csv file should contain "Male" "female" and "others" in the gender field. I tried calling some php functions within the code. But it didnt work. Is it possible? Can you help guys?

<?php

$conn = mysql_connect("localhost","root","");
mysql_select_db("bus",$conn);

$query = "SELECT * FROM booking";
$result = mysql_query($query);

$num_column = mysql_num_fields($result);        

$csv_header = '';
for($i=0;$i<$num_column;$i++) {
    $csv_header .= '"' . mysql_field_name($result,$i) . '",';
}   
$csv_header .= "\n";

$csv_row ='';
while($row = mysql_fetch_row($result)) {
    for($i=0;$i<$num_column;$i++) {
          //echo $i;                               this and the next line doesnt execute
         //echo '<script>myFunction()</script>'; 
        $csv_row .= '"' . $row[$i] . '",';
    }
    $csv_row .= "\n";
}
/* Download as CSV File */
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename=toy_csv.csv');
echo $csv_header . $csv_row;
exit;
?>
like image 317
Raavan Avatar asked Nov 08 '22 01:11

Raavan


1 Answers

Add the other fields that you expect for,

but this is how you will get the gender.

SELECT

IF (
    `booking`.gender = 1,
    "Male",

IF (
    `booking`.gender = 2,
    "Female",
    "Other"
)
) as gender
FROM
    `booking`;
like image 126
4EACH Avatar answered Nov 14 '22 22:11

4EACH