Download from database - php

I'm trying to download a list of email addresses from a database in WordPress to .CSV.
Anybody point me in the right direction:
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
$results = $wpdb->get_results( "SELECT * FROM table");
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)){
$data = json_encode($row);
}
outputCSV($data);
function outputCSV($data) {
$output = fopen("php://output", "w");
foreach ($data as $row) {
fputcsv($output, $row);
}
fclose($output);
}

This will do the trick:
header("Content-type: application/vnd.ms-excel");
header('Content-Disposition: attachment; filename="filename.csv"');
header("Pragma: no-cache");
header("Expires: 0");
echo '"Header 1","Header 2","Header 3"'."\n";
$results = $wpdb->get_results("SELECT * FROM `wp_newsletter_signup`");
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)){
echo '"' . $row['column1'] . '","' . $row['column2'] . '","' . $row['column3'] . '"' . "\n";
}
die();
Note my content type of application/vnd.ms-excel I use this as personal preference due to higher support in older windows machines, but you can continue to use text/csv - A list of mime types can be found here http://filext.com/file-extension/CSV

Change
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)){
$data = json_encode($row);
}
to
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)){
$data[] = $row;
}

Related

How to set text output alignment in MySQL Data export?

This is the SQL query
$query = "SELECT col1,col2,col3,col4,col5,col6,col7,col8 FROM table;
if (!$result = mysqli_query($con, $query))
{
exit(mysqli_error($con));
}
This is the part that outputs the text file
$filename = "output.txt";
$file = fopen($filename, "w");
foreach ($result as $rows)
{
fwrite($file, implode("\t",$rows).PHP_EOL);
}
header('Content-Description: File Transfer');
header('Content-type: text/tab-separated-values');
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
readfile($filename);
exit;
This is the current output:
This is the output that I need:
As commented out by #Slava Rozhnev and best way is to use csv like this:
<?php
$query = "SELECT col1,col2,col3,col4,col5,col6,col7,col8 FROM table";
$result = mysqli_query($con, $query);
$fp = fopen('file.csv', 'w');
while( $row = mysqli_fetch_array($result, MYSQLI_ASSOC) ) {
fputcsv($fp, $row);
}
fclose($fp);

PHP excel From MysQL DATABASE RECORDS

I am trying to download an excel file from MySql database records but i am not getting where i am wrong. Here is my code.
$sql_ft1 = "SELECT `Id`,`fname`,`lname` FROM users";
$rs_ft1 = mysql_query($sql_ft1) or die(mysql_error());
$total1=mysql_num_rows($rs_ft1);
$output.=' <table border="1">
<tr>
<th>Sr NO.</th>
<th width="120">User Name</th>
<th>Password</th>
</tr>
';` while($data = mysql_fetch_assoc($rs_ft1))
{`$output.= '
<tr>
<td>'.$data["Id"].'</td>
<td>'.$data["fname"].'</td>
<td>'.$data["lname"].'</td>
</tr>
'; }
$output.='</table>';
header("Content-type: application/xls");
header("Content-Disposition: attachment; filename=User_Detail_Reoprt.xls");
echo $output;
i made a new code with ur code as its giving php errors. I changed some " to ' and also in content header i changes filename " but it did not worked
$strtable.='<table border="1"><tr><th>Sr NO.</th><th width="120">User Name</th><th>Password</th>';
$sql_ft1 = "SELECT `Id`,`fname`,`lname` FROM users";
$rs_ft1 = mysql_query($sql_ft1) or die(mysql_error());
$total1=mysql_num_rows($rs_ft1);` while($data = mysql_fetch_assoc($rs_ft1)){$strtable.='<tr>
<td>'.$data["Id"].'</td>
<td>'.$data["fname"].'</td>
<td>'.$data["lname"].'</td>';
}
$strtable.='</tr>';
$strtable.='</table>';
echo $strtable;
$data = ob_get_contents();`
ob_end_clean();
header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename=User_Detail_Reoprt.xls");`header("Pragma: no-cache");
header("Expires: 0");
print $data;
echo $filename;
Try this,
$strtable.="<table border="1"><tr><th>Sr NO.</th><th width="120">User Name</th><th>Password</th>";
$sql_ft1 = "SELECT `Id`,`fname`,`lname` FROM users";
$rs_ft1 = mysql_query($sql_ft1) or die(mysql_error());
$total1=mysql_num_rows($rs_ft1);
$strtable.="<tr>
<td>$data["Id"]</td>
<td>$data["fname"]</td>
<td>$data["lname"]</td>";
$strtable.="</tr>";
$strtable.="</table>";
echo $strtable;
$data = ob_get_contents();
ob_end_clean();
header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename="User_Detail_Reoprt.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$data";
change your variable and check result hope it work
$this->excel->setActiveSheetIndex(0);
$filename = "myfile.xls";
$header = array("coulmn1","column2");
$list = array ($header);
foreach($query_result as $result_view){
$list[] = array($result_view->value1,$result_view->value2,
}
$this->excel->getActiveSheet()->fromArray($list);
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
$objWriter->save($filename);
echo $filename;

Wordpress - export a mysql table to csv with column headers

I am able to download a file in csv format for my table , but how to add column headers to the same file .
The current code is following -
// load wpdb
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-load.php';
global $wpdb;
$table = $_POST["table_name"];// table name
$file = 'database_csv'; // csv file name
$results = $wpdb->get_results("SELECT * FROM $wpdb->prefix$table",ARRAY_A );
if(count($results) > 0){
foreach($results as $result){
$result = array_values($result);
$result = implode(", ", $result);
$csv_output .= $result."\n";
}
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
header("Pragma: no-cache");
header("Expires: 0");
print $csv_output;
exit;
I was able to do it by first getting column names and then assigning it to final output :
$table_name = $wpdb->prefix.$_POST["table_name"];// table name
$file = 'database_csv'; // csv file name
$results = $wpdb->get_results("SELECT * FROM $table_name",ARRAY_A );
// get column names
$query = "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='".$wpdb->dbname."' AND `TABLE_NAME`='".$table_name."'";
$columnNamesList = $wpdb->get_results($query);
foreach ( $columnNamesList as $column_name ) {
$csv_output.=$column_name->COLUMN_NAME.",";
}
// remove last additional comma
$csv_output = substr($csv_output,0,strlen($csv_output)-1);
// start dumping csv rows in new line
$csv_output.="\n";
if(count($results) > 0){
foreach($results as $result){
$result = array_values($result);
$result = implode(", ", $result);
$csv_output .= $result."\n";
}
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
header("Pragma: no-cache");
header("Expires: 0");
print $csv_output;
exit;

CodeIgniter: Export data from database into excel and download

I'm working on a project, that requires exporting data from MYSQL DB depending on the multiple conditions. I am referring this:
This is my source code:
public function exportExcelData($records)
{
$heading = false;
if (!empty($records))
foreach ($records as $row) {
if (!$heading) {
// display field/column names as a first row
echo implode("\t", array_keys($row)) . "\n";
$heading = true;
}
echo implode("\t", ($row)) . "\n";
}
}
public function fetchDataFromTable()
{
$query =$this->db->get('one_piece_characters'); // fetch Data from table
$allData = $query->result_array(); // this will return all data into array
$dataToExports = [];
foreach ($allData as $data) {
$arrangeData['Charater Name'] = $data['name'];
$arrangeData['Charater Profile'] = $data['profile'];
$arrangeData['Charater Desc'] = $data['description'];
$dataToExports[] = $arrangeData;
}
// set header
$filename = "dataToExport.xls";
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"$filename\"");
$this->exportExcelData($dataToExports);
}
If I use it without any where clause, it is giving entire table.
If i use only single where clause, it works good.
Bur, if I use multiple where conditions. it gives me a blank excel sheet.
Does anyone have any idea regarding how to make it work with multiple where conditions?
Try using this code on your model file:
function createcsv(){
$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');
$delimiter = ",";
$newline = "\r\n";
$filename = "filename.csv";
$query = "SELECT * FROM YourTable"; //USE HERE YOUR QUERY
$result = $this->db->query($query);
$data = $this->dbutil->csv_from_result($result, $delimiter, $newline);
force_download($filename, $data);
}
// ecport contect list in csv ,
public function cnt_explode(){
$csvData[] =array( "Name", "Email Id","Mobile No.","Event", "City","location","No of guest","Event Date","Budget",
"Venue Type","Food","Drink","Description","Date");
$data = $this->contact_model->get_contact(NULL);
foreach($data as $cnt){
$csvData[]=array(
$cnt->name ,$cnt->email, $cnt->mobile_no, $cnt->event, $cnt->city, $cnt->location, $cnt->no_guest,$cnt->event_date,$cnt->budget, $cnt->venue_type,
$cnt->food, $cnt->drink, $cnt->description,$cnt->created_on,
);
}
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=venuexpo_".time().".csv");
header("Content-Transfer-Encoding: binary");
$df = fopen("php://output", 'w');
array_walk($csvData, function($row) use ($df) {
fputcsv($df, $row);
});
fclose($df);
}
///------------ downlode csv done --------------

Form downloads same ZIP over and over

Thanks to the users community on this forum, I wrote a very simple web form that allows my user to view text files from within their Internet browser.
I have now two functions whereby the text files returned by the search are compressed into a ZIP. Here's my code
function getFilesFromSite() {
$result = null;
$ZIPresult = null;
if (empty($_POST['DBSite'])) { return null; }
$mydir = MYDIR;
$dir = opendir($mydir);
$DBSite = $_POST['DBSite'];
$getfilename = mysql_query("select filename from search_table where site='" . $DBSite . "'") or die(mysql_error());
while ($row = mysql_fetch_array($getfilename)) {
$filename = $row['filename'];
$result .= '<tr><td>' . $filename . '</td></tr>';
$ZIPresult .= basename($mydir) . '/' . $filename.' ';
}
if ($result) {
$result = "<table><tbody><tr><td>Search Results.</td></tr> $result</table>";
shell_exec("/bin/rm -f SearchResult.zip;/usr/bin/zip -9 SearchResult.zip ". $ZIPresult ." > /dev/null ");
//header for forced download
header("Pragma: public");
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
$fileName = 'SearchResult.zip';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Transfer-Encoding: binary");
header('Content-type: application/zip');
header("Content-length: " . filesize($fileName));
header('Content-Disposition: attachment; filename="' . $fileName . '"');
ob_start(); // Starts output buffering.
readfile($fileName); // "Outputs" the file.
$content = ob_get_flush(); // Grabs the output and assigns it to a variable.
print base64_encode($content);
}
function getFilesFromError() {
//Just a copy paste from above with different input parameter...
}
The problem is that the ZIP file with the contents from whatever search was done first gets downloaded over and over again. For instance, the results from getFilesFromSite() will always get downloaded even though I did a search with getFilesFromError() afterwards.
I suspect my headers are incorrectly set but I am not sure where.
PS: The new ZipArchive() library/class is not available on our production environment so I chose to use the Unix utility ZIP instead.
Using Base64 was actually not working for reasons well stated here. Instead, I turned zlib compression off and reverted back to using binary as output format. Finally, I set Content-Type to application/octet-stream in my header. Everything is working fine now ; here's my code:
function getFiles() {
ini_set('zlib.output_compression', 'Off');
$result = null;
$ZIPresult = null;
$cleanup = null;
$output = null;
$fileName = null;
//remove old zip if any
$cleanup = shell_exec("/bin/rm -f SearchResult.zip");
error_log("SHELL OUTPUT=>" . $cleanup, 0);
//test
if (empty($_POST['DBRIDs'])) { return null; }
$mydir = MYDIR; // set from the CONSTANT
$dir = opendir($mydir);
$DBRIDs = $_POST['DBRIDs'];
$getfilename = mysql_query("select /*! SQL_CACHE */ filename from automation where rid in (" . $DBRIDs . ")") or die(mysql_error());
while ($row = mysql_fetch_array($getfilename)) {
$filename = $row['filename'];
$result .= '<tr><td>' . $filename . '</td></tr>';
$ZIPresult .= basename($mydir) . '/' . $filename.' ';
}
if ($result) {
$result = "<table><tbody><tr><td>Search Results.</td></tr> $result</table>";
$output = shell_exec("/usr/bin/zip SearchResult.zip ". $ZIPresult ." ");
error_log("SHELL OUTPUT=>" . $output, 0);
$fileName = 'SearchResult.zip';
error_log("ZIP FILENAME=>" . $fileName, 0);
if (file_exists($fileName)) {
//header for forced download
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($fileName));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($fileName));
ob_clean();
flush();
readfile($fileName);
exit;
}
}
return $result;
}
Thanks to all for taking the time!!

Categories