export mysql data to excel using php ajax call - php

i am doing an ajax call and called a php page which is extracting data from a mysql table and need to convert it to excel and need to store in server folder only.
Now the problem is while doing the ajax call, its going to that php page and returning to the main page without creating the excel file.
But when i tested the php page directly then its creating the excel file and downloading it. But why its not working via ajax call.
This is my ajax call from previous page --
$.ajax({
type: "POST",
url: "admin-advertiser-details-exports.php?selectedColumns="+selectedColumns+"&excelColumn="+excelColumn,
contentType:false,
processData:false,
success:function(data){
alert('Export done');
}
});
And this is my php page which is exporting to excel --
<?php
session_start();
include 'db.php';
if(!isset($_SESSION))
{
$uname=$_SESSION['uname'];
}
else if(empty($_SESSION['uname']))
{
header('Location: index.php',TRUE);
}
$UserName = $_SESSION['uname'];
$UserID = $_SESSION['uid'];
$UserType = $_SESSION['utype'];
$selectedColumns = $_GET['selectedColumns'];
$excelColumn = $_GET['excelColumn'];
$array = explode('\t',$excelColumn);
$sql = "select ".$selectedColumns." from advertisers_details ad join user_details ud on ad.adv_manager=ud.user_id order by ad.adv_id asc";
$setRec = mysqli_query($linkID1, $sql);
$columnHeader = '';
foreach ($array as $value) {
$value = '"' . $value . '"' . "\t";
$columnHeader .= $value;
}
$setData = '';
while ($rec = mysqli_fetch_row($setRec))
{
$rowData = '';
foreach ($rec as $value)
{
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData) . "\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=advertiser_detail.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader) . "\n" . $setData . "\n";
?>
If i am running this php page directly the i am getting the excel file, but via ajax call its not working.

Hope this example work best for you.
I have used window.open and set url of target file with parameter.
JS code used
/* Export Orders */
$(document).on('click','#btn_export_delivery_order',function(){
var first_input = $('#name_email_order_search').val();
var date_range = $('#reportrangeorder').val();
var order_status = $('#order_status').val();
window.open("ajax_responce.php?method_name=export_orders&shop="+ shop+"&first_input=" + first_input + "&date_range=" + date_range + "&order_status=" + order_status + "", '_blank');
});
Code used in ajax_response.php
public function export_orders(){
ob_start();
if (isset($_GET['shop']) && $_GET['shop'] != '') {
$export = array();
$export_data = array();
$shopinfo = $this->get_settings($_GET['shop']);
$store_client_id = $shopinfo['store_client_id'];
$date_format = $shopinfo['date_format_first'];
$options_arr = array("skip" => 0, "limit" => 99999);
$where = $this->where_to_clause_export_search($store_client_id, $_GET);
$fullfilment_status_array = array('Unfulfilled','Fullfill','Partially fullfill','Cancelled');
$export_result = $this->select_result(TABLE_ORDERS, '*', $where, $options_arr);
foreach($export_result['data'] as $row){
$export['Name'] = $row['order_name'];
$export['Billing Name'] = $row['first_name'] . ' ' . $row['last_name'];
$export['Email'] = $row['email'];
$export['Fulfillment Status'] = $fullfilment_status_array[$row['status']];
$export['Total'] = $row['total'];
$export['Created at'] = date($date_format, strtotime($row['created_at']));
$export['Delivery Status'] = $row['delivery_status'] == 0 ? 'Pending' : 'Delivered';
$export['Delivery Date'] = date($date_format, strtotime($row['delivery_date']));
$export['Delivery Time'] = (isset($row['delivery_time']) && $row['delivery_time'] != '') ? $row['delivery_time'] : '-';
$export_data[] = $export;
}
/* Export Data */
$filename = "orders_export.csv";
$f = fopen('php://output', 'w');
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename=' . $filename);
$outputdata = $export_data;
$firstLineKeys = false;
foreach ($outputdata as $row) {
if (empty($firstLineKeys)) {
$firstLineKeys = array_keys($row);
fputcsv($f, $firstLineKeys);
$firstLineKeys = array_flip($firstLineKeys);
}
fputcsv($f, $row);
}
fclose($f);
ob_end_flush();
exit();
}
}
This code is tested well and working fine.

Related

“How to export other next file‘ after 2000 rows data

I am using PHP for export CSV file this is working, but i export 2000 or greater rows how to create automatic next CSV file.
How to Move other file on after 2000 rows?
<?php
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename = records.csv');
echo $header = "Name";
echo "\r\n";
$sql = mysql_query(“Select * from table”);
while ($getData = mysql_fetch_assoc($sql)) {
echo '"'.$name.'"';
echo "\r\n";
}
exit;
?>
You can use array_chunk function to keep the records of 2000 and export them in csv.
For example
$rowData = [
[1,2,3],
[11,21,31],
[21,22,32],
[31,42,73],
[111,222,333]
];
foreach(array_chunk($rowData, 2) as $key => $records){
$file_name = 'export_data_'.$key.'.csv';
writeToCsv($file_name,$records);
}
//funtion to export data to csv
function writeToCsv($fileName, $rowData){
$fp = fopen($fileName, 'w');
foreach ($rowData as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
}
In your case use array_chunk($rowData, 2000)
<?php
$rowLimit = 2000;
$fileIndex = 0;
$i = 1;
$handle = null;
$fileList = array();
$timestampFolder = strtotime("now").'/';
mkdir($timestampFolder);
$sql = mysql_query("Select * from table");
while ($getData = mysql_fetch_assoc($sql)) {
if( ($i%$rowLimit) == 1) {
$fileIndex+=1;
if(!is_null($handle)) {
fclose($handle);
}
$fileName = "records".$fileIndex.".csv";
$handle = fopen($timestampFolder.$fileName, "a");
$fileList[] = $fileName;
}
fputcsv($handle, $getData);
$i++;
}
foreach($fileList as $file) {
echo ''.$file.'<br>';
}

CSV Download not working for all pages

I have a website that I created for reports. There are basically 3 reports. I have a button on each page that calls another PHP page that will download the results of the query that fills the page into a CSV file. This works fine on one page, but on the other two it gives me an error when trying to open. It says:
The file format and extension of 'FileName' don't match. the file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?
I click yes, then get this:
Excel has detected that 'FileName' is a SYLK file, but cannot load it. Either the file has errors or it is not a SYLK file format. Click OK to try to open the file in a different format.
I click OK and it opens fine.
Where as on the other page it just opens.
Here's most of the ExportToExcel.php
switch ($_POST['ExportToExcel'])
{
case "QDef":
$tsql = "select Id,QSrc,QName,QDef,isActive,RunReport,FilePath from pmdb.v_QDefs order by Id";
$hsql = "select Headings from TableHeadings where TableName = 'v_QDefs' and Headings != 'Edit' order by ID";
break;
case "TableUpdates":
$tsql = "select ID, TableName, UpdateDate from pmdb.TableUpdates order by UpdateDate";
$hsql = "select Headings from TableHeadings where TableName = 'TableUpdates' and Headings != 'Edit' order by ID";
break;
}
$filename = $_POST['ExportToExcel'];
header("Content-Type: application/x-csv");
header("Content-Disposition: attachment; filename=$filename.csv");
//define separators (defines columns in excel)
$sep = ",";
$br = "\r\n"; //line break
$getHeadings = $conn->query($hsql);
$rHeadings = $getHeadings->fetchALL(PDO::FETCH_ASSOC);
$headings = array();
$NumHeadings = count($rHeadings);
for ($i = 0;$i < $NumHeadings; $i++)
{
$headings[] = $rHeadings[$i]["Headings"];
}
//start of printing column names as names of SQL fields
foreach($headings as $Heading => $value)
{
echo "$value" . $sep;
}
//end of printing column names
echo $br; //separate the headers and the data
foreach($conn->query($tsql) as $row)
{
for ($i = 0;$i < $NumHeadings;$i++)
{
$CommentPos = strpos($rHeadings[$i]["Headings"],"comment");
$NewLines = array("\r\n","\n\r","\n","\r");
$UseValue = str_replace($NewLines, " ",$row[$i]);
$UseValue = str_replace('"', "'",$row[$i]);
$pos = strpos($UseValue,",");
if ($CommentPos === FALSE || $pos === FALSE || isset($UseValue))
{
echo '"' . $UseValue . '"' . $sep;
}
else
{
echo $UseValue . $sep . "Not quoted";
}
}
echo $br;
}
I have a include at the top that has the connection string for connecting to my MSSQL DB, which does work, or there'd be nothing displayed on the page to begin with.
I just con't figure out why the page doesn't work the same way for all reports when they are all calling the page the same way.
EDIT again
I tried several ideas from below and now I have this:
$filename = $_POST['ExportToExcel'] . '.csv';
$Opened = fopen($filename,'w');
header("Content-Type: text/csv; charset=utf-8'");
header("Content-Disposition: attachment; filename=$filename");
fputcsv($Opened,$headings);
foreach($conn->query($tsql) as $row)
{
fputcsv($Opened,$row);
}
fclose($Opened);
Which still gives me a blank spreadsheet. So obviously I'm still doing something wrong?
Nevermind, I updated the Headings for all the tables that I am trying to export so that the first column is no longer ID, but is instead Id. Since it's no longer all caps it is working fine without the fputcsv since that isn't doing anything for me anyhow.
$filename = $_POST['ExportToExcel'] . '.csv';
header("Content-Type: text/csv; charset=utf-8'");
header("Content-Disposition: attachment; filename=$filename");
//define separators (defines columns in excel)
$sep = ",";
$br = "\r\n"; //line break
$getHeadings = $conn->query($hsql);
$rHeadings = $getHeadings->fetchALL(PDO::FETCH_ASSOC);
$headings = array();
$NumHeadings = count($rHeadings);
for ($i = 0;$i < $NumHeadings; $i++)
{
$headings[] = $rHeadings[$i]["Headings"];
}
//start of printing column names as names of SQL fields
foreach($headings as $Heading => $value)
{
echo "$value" . $sep;
}
foreach($conn->query($tsql) as $row)
{
for ($i = 0;$i < $NumHeadings;$i++)
{
$CommentPos = strpos($rHeadings[$i]["Headings"],"comment");
$NewLines = array("\r\n","\n\r","\n","\r");
$UseValue = str_replace($NewLines, " ",$row[$i]);
$UseValue = str_replace('"', "'",$row[$i]);
$pos = strpos($UseValue,",");
if ($CommentPos === FALSE || $pos === FALSE || isset($UseValue))
{
echo '"' . $UseValue . '"' . $sep;
}
else
{
echo $UseValue . $sep . "Not quoted";
}
}
echo $br;
}

Trying to print a report from SQL Database?

Trying to generate a report form data base to be exported as an excel file, but I keep getting 0 results when there is data in the database. Can anyone take a look at the code and let me know what I have wrong. the code needs to go into a server that is running php 5.4+ from 4+
<?php
//set date
$date = date("m/d");
$course_report = $_POST['course_report'];
$course_info = explode('~',$course_report);
$course_info[0]; // course_id
$course_info[1]; // course_date
$select = "SELECT DISTINCT * FROM registrants WHERE (paid='Y' AND course_id = '$course_info[0]' AND course_date = '$course_info[1]')";
$result = mysqli_query($dbc, $select);
// first get the header row
while($row = mysqli_fetch_assoc($result)) {
$course = $row['course'];
$coursedate = $row['course_date'];
$export = mysql_query($select);
$fields = mysql_num_fields($export);
}
// Get header
$fields = isset($_POST['fields']);
for ($i = 0; $i < $fields; $i++) {
$header .= mysqli_field_name($export, $i) . "\t";
}
// Then get all the rows of data
$export = isset($_POST['export']);
while($row = mysqli_fetch_row($result)) {
$line = '';
foreach($row as $value) {
if ((!isset($value)) OR ($value == "")) {
$value = "\t";
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim($line)."\n";
}
$data = isset($_POST['data']);
$data = str_replace("\r","",$data);
// Check for blank data set
if ($data == "") {
$data = "\n(0) Records Found!\n";
}
// end building the data
$header = isset($_POST['header']);
$course = isset($_POST['course']);
$file_name = $course . "_downloaded_" . $date;
header("Content-type: application/x-msdownload");
//header("Content-Disposition: attachment; filename=Registrar_101.txt");
header("Content-Disposition: attachment; filename=$file_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
// }
?>
This says it's only supposed to get one row, but it's actually going to get all rows.
// first get the header row
while($row = mysqli_fetch_assoc($result)) {
$course = $row['course'];
$coursedate = $row['course_date'];
$export = mysql_query($select);
$fields = mysql_num_fields($export);
}
Then for each row you're inexplicably re-exectuing the query with mysql_query()
and at this point I've stopped looking because you really need to clean up the logic here if the rest of the script is going to make any sense at all.
I'm not sure what you think is happening under "first get the header row". The query is retrieving records from the Registrants table. Where do you think a "header row" is coming from? Are you thinking that you are going to get a row back from the query with the column headers, i.e. the names of the fields? If so, that's not how it works.
Then within this loop you re-execute the query for every record. Why? What does that accomplish? Then you get the count of the number of fields from this inner query and put it in $fields. But you never use this value. After the loop, you promptly overwrite it.
Do you understand that isset() returns true or false? You seem to think it returns a string.
$_POST gets a value that was submitted on a form from a web page. You seem to be thinking that it's going to give you values from your query or something.
I'm not sure exactly what you're trying to accomplish, but I think the core of your program should look something like this:
<?php
//set date
$date = date("m/d");
$course_id = $_POST['course'];
$course_date = $_POST['course_date'];
// You really should use mysqli_real_escape_string to escape input strings,
// but let's skip that point for now
// Also, it's generally bad form to use "select *", as then you have no idea what
// fields you will get back. Better to list exactly what you want.
$select = "SELECT DISTINCT * FROM registrants WHERE (paid='Y' AND course_id = '$course_id' AND course_date = '$course_date')";
// This assume the db is already open as $dbc
$result = mysqli_query($dbc, $select);
// build header row
$header = '';
$field_count = mysqli_num_field($result);
for ($i = 0; $i < $field_count; $i++) {
$finfo = mysqli_fetch_field_direct($result,$i);
$name = $finfo->name;
$header .= $name . "\t";
// I'm not familiar with a mysqli_field_name function and couldn't find it in the docs.
// Whatever.
}
$data = $header . "\n";
// Then get all the rows of data
while($row = mysqli_fetch_row($result)) {
$line = '';
foreach($row as $value) {
if (!isset($value) OR $value == "") {
$value = "\t";
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
$line .= $value;
}
$data .= trim($line)."\n";
}
... and then whatever you need to do with this thing ...

PHP Mysql table conversion to excel:The file you are trying to open is in a different format than specified by the extension

I have a code that converts mysql table to excel sheet. It converts and the excel sheet is downloaded but whenever I try to open the file it gives an error msg in excel 2007:"The file you are trying to open is in a different format than specified by the extension...".The excel sheet opens after I click on 'Yes' but it is nothing but a white blank sheet.I have seen the similar posts but none of them solves my problem...Please help...Thank you
<?php
include('dbcon.php');
?>
<?php
$sql = "SELECT * FROM stu_gen_info";
$rec = mysql_query($sql) or die (mysql_error());
$num_fields = mysql_num_fields($rec);
for($i = 0; $i < $num_fields; $i++ )
{
$header .= mysql_field_name($rec,$i)."\\t";
}
while($row = mysql_fetch_row($rec))
{
$line = '';
foreach($row as $value)
{
if((!isset($value)) || ($value == ""))
{
$value = "\\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\\n";
}
$data = str_replace("\\r" , "" , $data);
if ($data == "")
{
$data = "\\n No Record Found!\n";
}
header("Content-Type: application/vnd.ms-excel");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=reports.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\\n$data";
?>
try adding this
header("Content-Type: application/vnd.ms-excel");

Html Codes In Exported Data [PHP]

I am trying to export the data got from my database.
The problem is that the data comes with html codes.
I just want to export the data without html codes.
Note: My database doesn't have any html code.
$exported_db_datas (global array variable) is created like this:
while($row = mysql_fetch_array($resultset,MYSQL_ASSOC))
{
$resultsarray[$rowcount] = $row;
$exported_db_datas[$rowcount] = $row;
/*foreach($resultsarray[$rowcount] as $column)
{
$resultsarray2[$rowcount][] = $column;
}*/
$rowcount++;
}
Export codes :
$export_file = "export_phisto";
if ($format == "CSV")
{
$file = $export_file.".csv";
$separator = ",";
}
elseif ($format == "TAB")
{
$file = $export_file.".tab";
$separator = "\t";
}
elseif ($format == "TXT")
{
$file = $export_file.".txt";
$separator = "\t";
}
else// XLS
{
$file = $export_file.".xls";
$separator = "\t";
}
header("Content-Disposition: attachment; filename=\"$file\"");
header("Content-Type: text/plain");
$flag = false;
foreach($exported_db_datas as $row)
{
if(!$flag)
{
// display field/column names as first row
echo implode($seperator, array_keys($row)) . "\r\n";
$flag = true;
}
echo implode($seperator, array_values($row)) . "\r\n";
}
Note: Even if I don't use print $data, exported data has html codes of the web site without data.
How can I just export the data I get from database?
Example exported data is was here.
Use strip_tags
$exported_db_datas[$rowcount] = strip_tags($row);
just use strip_tags() in this line $exported_db_datas[$rowcount] = $row; like so: $exported_db_datas[$rowcount] = strip_tags($row);
PS: don't use the mysql_* extension, it was deprecated, see the red warning box here

Categories