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
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');
?>

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.