Click here to Skip to main content
15,914,419 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello....

How to export mysql table into a csv file in php??
Posted
Comments
Thomas ktg 21-Nov-13 1:58am    
There are so many resources available on the net if you search through google or other search engines.
Arun-23 23-Nov-13 1:09am    
Try this..

SELECT order_id,product_name,qty
FROM orders
INTO OUTFILE '/tmp/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'

http://www.tech-recipes.com/rx/1475/save-mysql-query-results-into-a-text-or-csv-file/
Member 9621354 29-Nov-13 6:10am    
And now how to make this file downloadable to local machine???
Member 9621354 29-Nov-13 6:42am    
This query is not working .............. it is givign error

1 solution

Hope so this soln works for your problem

PHP
<?php

// Database Connection

$host="localhost";
$uname="root";
$pass="";
$database = "a2zwebhelp";

$connection=mysql_connect($host,$uname,$pass);

echo mysql_error();

//or die("Database Connection Failed");
$selectdb=mysql_select_db($database) or
die("Database could not be selected");
$result=mysql_select_db($database)
or die("database cannot be selected <br>");

// Fetch Record from Database

$output = "";
$table = ""; // Enter Your Table Name
$sql = mysql_query("select * from $table");
$columns_total = mysql_num_fields($sql);

// Get The Field Name

for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\n";

// Get Records from the table

while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}

// Download the file

$filename = "myFile.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);

echo $output;
exit;

?>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900