Wednesday, May 13, 2015

Export Mysql table records to the to csv file useing php

To export the sql table data to csv file

Below code you can user to expert and sql table data to the  csv file.

<?php 
$table = 'wp_users';  // table name here
$filename = tempnam(sys_get_temp_dir(), "csv");

$conn = mysql_connect("localhost", "root", "");    // data base connection crediential here
mysql_select_db("database",$conn);   // connect with the my sql database

$file = fopen($filename,"w");

// Write column names
$result = mysql_query("show columns from $table ",$conn);
for ($i = 0; $i < mysql_num_rows($result); $i++) {
    $colArray[$i] = mysql_fetch_assoc($result);
    $fieldArray[$i] = $colArray[$i]['Field'];
}
fputcsv($file,$fieldArray);

// Write data rows
$result = mysql_query("select * from $table",$conn);
for ($i = 0; $i < mysql_num_rows($result); $i++) {
    $dataArray[$i] = mysql_fetch_assoc($result);
}
foreach ($dataArray as $line) {
    fputcsv($file,$line);
}

fclose($file);

header("Content-Type: application/csv");
header("Content-Disposition: attachment;Filename=user_details.csv");

// send file to browser
readfile($filename);
unlink($filename);

?>

No comments:

Post a Comment