Sean Stevens Sean Stevens - 1 month ago 8
PHP Question

exporting a mysql query in php version 4 to a csv

Edit on my original post. I found the answer!!!! with help:)

I now have this working by using the below code with thanks for the advice on this in the comments:

<?php

$f = fopen('incident_csv\test.csv', 'w');

$query = "
select column1, column2, column3
from table
where columns = values
";

$var1 = mysql_query($query, $database connection variable);

/* From Monkey Zeus */

$csv_lines = array();

// Loop your records from the DB
while ($row = mysql_fetch_assoc($var1)){

$columns = array();

// Loop each column for the row
foreach($row as $k=>$v){
// Surround column item in double-quotes and escape double-quotes with double-double-quotes
$columns[] = '"'.str_replace('"', '""', $v).'"';
}

// Join on a comma
$csv_lines[] = implode(',', $columns);
}

// Create full CSV file by joining on a newline
$csv_file_string = implode("\n", $csv_lines);

/* From Monkey Zeus */

fwrite($f, $csv_file_string);

?>

Answer

You can do this:

$csv_lines = array();

// Loop your records from the DB
while ($row = mysql_fetch_array($var1)){

    $columns = array();

    // Loop each column for the row
    foreach($row as $k=>$v){
        // Surround column item in double-quotes and escape double-quotes with double-double-quotes
        $columns[] = '"'.str_replace('"', '""', $v).'"';
    }

    // Join on a comma
    $csv_lines[] = implode(',', $columns);
}

// Create full CSV file by joining on a newline
$csv_file_string = implode("\n", $csv_lines);
Comments