Downloading records as CSV file

We can download the data of a table to a CSV file and ask the user to save the same in local system. This is required for backup purposes and for developing several other applications.

What is .csv file

csv files, (comma-separated values or  character-separated values ) example : my_file.csv are text files and are popular form of data portability, download or upload for database tables. Here usually one record per line is used with comma as separator between each field.

Example of CSV file

1,"John Deo",Four,75,female
2,"Max Ruin",Three,85,male

We will use our student table for this example and show how to download or save the CSV file.

We have used file header control to prompt for or to start data download.

<?php
require "config.php"; // Connection string
dataConnect(); // Connect to Database

header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename="my-student-data.csv"");
$data = "";

$query = $dbo->prepare("select * FROM student");
$query->execute();

for($i=0; $row = $query->fetch(PDO::FETCH_NUM); $i++){
$data.="$row[0],$row[1],$row[2],$row[3],$row[4]"."\n";
}

unset($dbo);
unset($query);

echo $data;
?>

In the above script PDO data connection string and PDO class to collect records

Download sql dump of this student table
Visitors Rating
Your Rating




Post Comment This is for short comments only. Use the forum for more discussions.








HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2019 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer