0

I Try this solution to export from my database to CSV and it work but all Data are exported in one colones. I would like that compose me in The CSV like in the table data base. What is the problem in this code ?

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

?>
2
  • 1
    instead of \n use the constant PHP_EOL Commented Jan 29, 2014 at 8:58
  • ... which is the same on UNIX and doesn't solve OPs problem if he's transfering from Unix to Windows ... Commented Jan 29, 2014 at 9:08

1 Answer 1

1

If you use "\n" as a line separator and open that file in i.e. notepad.exe, this will not be properly recognized as "carriage return linefeed" and the entire file seems to be just "one big line" - but actually it isn't!

You may terminate lines with "\r\n" to prevent this effect.

In order to have this automatically recognized by i.e. Excel, use ; as field separator instead of ,.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.