||01-10-2012 01:57 PM
Export information from a database to a CSV spreadsheet with PHP
Let’s assume that you already have a database setup with a table called “users” and you want to export users and their email addresses to a CSV file.
// Connect and query the database for the users
$conn = new PDO("mysql:host=localhost;dbname=mydatabase", 'myuser', 'mypassword');
$sql = "SELECT username, email FROM users ORDER BY username";
$results = $conn->query($sql);
// Pick a filename and destination directory for the file
// Remember that the folder where you want to write the file has to be writable
$filename = "/tmp/db_user_export_".time().".csv";
// Actually create the file
// The w+ parameter will wipe out and overwrite any existing file with the same name
$handle = fopen($filename, 'w+');
// Write the spreadsheet column titles / labels
// Write all the user records to the spreadsheet
foreach($results as $row)
fputcsv($handle, array($row['username'], $row['email']));
// Finish writing the file
|All times are GMT -4. The time now is 04:37 AM.
Powered by vBulletin
Copyright ©2000 - 2014, Jelsoft Enterprises Ltd.
User Alert System provided by
Advanced User Tagging (Pro) -
vBulletin Mods & Addons Copyright © 2014 DragonByte Technologies Ltd.
© WebHostingTalk, 1998 - 2014. All Rights Reserved.