Jump to content

Convert MySQL to CSV using PHP


homeslice

Recommended Posts

HELP! (& hello!)

 

First post here because I'm tearing what little hair I have left out.

 

I need some help extracting data from a MySQL table and inserting it into a CSV file using a PHP script. I can do this.

 

Problem is, I have a MySQL table with 8 fields. I only want to extract 2 of these fields and their results into the CSV file.

 

Please help.

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/95780-convert-mysql-to-csv-using-php/
Share on other sites

This is what I have so far.

 

Its modified from some other code and exports perfectly the entire table

 

<?
// Connect database
$database="fyp";
$table="siteform";
mysql_connect("localhost","root","");
mysql_select_db("fyp");

$result=mysql_query("select * from $table");

$out = ''; 

// Get all fields names in table "siteform" in database "fyp".
$fields = mysql_list_fields(fyp,$table);

// Count the table fields and put the value into $columns. 
$columns = mysql_num_fields($fields);


// Put the name of all fields to $out. 
for ($i = 0; $i < $columns; $i++) {
$l=mysql_field_name($fields, $i);
$out .= '"'.$l.'",';
}
$out .="n";

// Add all values in the table to $out. 
while ($l = mysql_fetch_array($result)) {
for ($i = 0; $i < $columns; $i++) {
$out .='"'.$l["$i"].'",';
}
$out .="n";
}

// Open file export.csv.
$f = fopen ('export.csv','w');

// Put all values from $out to export.csv. 
fputs($f, $out);
fclose($f);

header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="export.csv"');
readfile('export.csv');
?>

If you only want to put two of the fields in the table, only retrieve those two fields with your query:

<?php
$q = "select field1,field2 from $table";
$rs = mysql_query($q) or die("Problem with the query [$q]<br>" . mysql_error());
$fp = fopen('export.csv','w');
fwrite($fp,"field1,field2\n");
while ($rw = mysql_fetch_assoc($rs))
    fwrite($fp,'"'.implode('","',$rw) . '"' . "\n");
fclose($fp);
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="export.csv"');
readfile('export.csv');
?>

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.