Skip to content
WJunction - Webmaster Forum

PHP - MySQL query to CSV export

Status
Not open for further replies.
Hi

I need some advise how to achieve this.. there is a link "Click here to generate CSV" when someone clicks that link, it should execute a query and export that sql query result to a CSV file..

any guidance pls?

Sam
 

2 comments

google says:
PHP:
mysql_connect($server, $login, $password);
mysql_select_db($db);

$fp = fopen($filename, "w");

$res = mysql_query("SELECT * FROM $table");

// fetch a row and write the column names out to the file
$row = mysql_fetch_assoc($res);
$line = "";
$comma = "";
foreach($row as $name => $value) {
    $line .= $comma . '"' . str_replace('"', '""', $name) . '"';
    $comma = ",";
}
$line .= "\n";
fputs($fp, $line);

// remove the result pointer back to the start
mysql_data_seek($res, 0);

// and loop through the actual data
while($row = mysql_fetch_assoc($res)) {
   
    $line = "";
    $comma = "";
    foreach($row as $value) {
        $line .= $comma . '"' . str_replace('"', '""', $value) . '"';
        $comma = ",";
    }
    $line .= "\n";
    fputs($fp, $line);
   
}

fclose($fp);
 
Status
Not open for further replies.

About the author

E
Active Member · Joined
I'm a Webmaster as well as Sys Admin Coding
136
Messages
3
Reactions
18
Points

Advertise on WJunction

Reach 1000's of webmasters, hosts & affiliates. Banner & sponsored-thread slots available.

Contact us
Back
Top Bottom