export table result to CSV - php

trying to export my table to CSV file but I seem to be lost on what am doing wrong,
I have my loaddata.php that has table that shows fields
I have my Connection.php that will have database connection
but when I run result what am getting is it exporting CSV with columns, but data is is bring back loaddata.php page with HTML formatting and every result
I have tried moving the included "loaddata.php" than I get brought back blank excel page with columns
<?php include('connection.php');
if(isset($_POST["export"])){
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=loaddata.csv');
$output = fopen("php://output", "w");
fputcsv($output, array(
'row number',
'Position ID',
'Description',
'firstname',
'lastname',
'country ',
'PhoneNumber'));
include ("loaddata.php")
$sqlcsv = "SELECT * FROM employeeTable";
$resultcsv = mysqli_query($conn,$sqlcsv)
or die('Invalid query sqlcsv: ' . mysqli_error());
while ($row = mysqli_fetch_assoc($resultcsv))
{
fputcsv($output, $row);
}
fclose($output);
}
?>

Related

How do I seperate CSV headers and columns in PHP

I am trying to create a csv with PHP, that separate the the headers and columns.
Currently I am able to create the csv and dump the data, but each row in dumped into one cell.
The result is:
I expected this:
Here is my code
<?php
// Load the database configuration file
require_once('db/connect_db.php');
//$time = date('Y-m-d:').preg_replace("/^.*\./i","", microtime(true));
$time = date('Y-m-d');
$dteTimetamp = date('Y-m-d');
// Fetch records from database
$find = $conn->prepare("SELECT School, SchoolAddress, School_Email, Principle_Name, Reception_Number, QuantityFingerPrintScanner, InvoiceNumber from School");
$find->execute();
$udonr = "$dteTimetamp" . "Request";
//$filename = "$udonr.csv";
// Create a file pointer
$f = fopen(dirname(__FILE__).'/testfolder/'.$udonr.'.csv', 'w');
// Set column headers
$header = array('School Name', 'Contact Person', 'Contact Number', 'School Address', 'Number of scanners to deliver', 'Invoice Nuber');
fputcsv($f, $header);
// Output each row of the data, format line as csv and write to file pointer
while($row = $find->fetch(PDO::FETCH_ASSOC)){
$lineData = array($row['School'], $row['Principle_Name'], $row['Reception_Number'], $row['SchoolAddress'], $row['QuantityFingerPrintScanner'], $row['InvoiceNumber']);
fputcsv($f, $lineData);
// Set headers to download file rather than displayed
//header('Content-Type: text/csv');
// header('Content-Disposition: attachment; filename="' . $filename . '";');
//output all remaining data on a file pointer
fpassthru($f);
}
//exit;
#FROSIT is right. Excel is kinda dumb about opening CSV files, especially ones with comma separator (ironically).
Your file looks good but if you need to have it automatically open in Excel (e.i. someone else will need to open it), you might want to find which one is the default separator for Excel and set that in your script.

PHP code to export to excel specific filtered date

I am trying to write a simple PHP code to export to excel the data selected between two dates. On clicking the 'Export to Excel' button in the HTML page which will redirect to php file with the below code, my excel is not getting downloaded. Can someone tell me where the error is and what modification needs to be made. Tell me in the simplest way possible.
<?php
include ("conn.php");
if(isset($_POST["export"]))
{
$connect = mysqli_connect("localhost", "root", "", "cruddatabase");
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen("php://output", "w");
fputcsv($output, array('ID Company Name','Company Type','Name','Email','Contact Number','Anniversary Date','Organisation Name','Meeting','Timeline For Conversation','Currency','Card','Locations'));
$query = "SELECT * FROM crudtable WHERE adate >= '$fdate' AND adate <= '$tdate' ORDER BY adate DESC";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_assoc($result))
{
fputcsv($output, $row);
}
fclose($output);
}
?>

Printing MySQL query results to CSV file in PHP

I'm having a problem writing the results of a MySQL query to a file using php. There are definitely results from the search, and the file is created, but when you open the file it's empty. I think it's something to do with how I'm writing to the file, but I'm not sure.
$result = mysql_query($compsel);
if(!result) die("unable to process query: " . mysql_error());
$fp = fopen('results.csv','w');
mysql_data_seek($result,0); //set data pointer to 0
$rw = mysql_fetch_array($result, MYSQL_ASSOC);
print_r($rw);
foreach ($rw as $fields){
fputcsv($fp, $fields);
}
fclose($fp);
Thanks in advance!
Here's an example:
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));
// fetch the data
mysql_connect('localhost', 'username', 'password');
mysql_select_db('database');
$rows = mysql_query('SELECT field1,field2,field3 FROM table');
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
You can modify it to suit your needs.
Source: http://code.stephenmorley.org/php/creating-downloadable-csv-files/

Concatenate static value while exporting CSV file using fputcsv in PHP

I am using below code to export CSV file using fputcsv in PHP. Code works proper and CSV file generates. All the values/records are coming from database. But I want to add dollar ($) symbol with some of column values.
Code for exporting CSV file.
$filename1 = "All Months.csv";
ob_end_clean();
$fp1 = fopen('php://output', 'w');
ob_start();
header("Content-type: application/vnd.ms-excel");
header('Content-Disposition: attachment; filename='.$filename1);
fputcsv($fp1, array('Month', 'Year', 'Total Production', 'Credit Adjustments', 'Net Production', 'Hygiene Production', 'Collections', 'Account Receivable Total', 'New Patients', 'Break Even Points', 'Net Income', 'Hygiene %'));
$query = $db->query("SELECT Month, Year, Total_Production, Credit_Adjustments, Net_Production, Hygiene_Production, Collections, AC_Receivable_Total, New_Patients, Break_Even_Points, Net_Income, Hygiene FROM clientsdata WHERE Client_Id = '".$userID."'");
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
fputcsv($fp1, $row);
}
exit();
Snapshot of exporting file -
If you want just to add $ sign you can do it this way:
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$row['the_field_you_want'] = '$'.$row['the_field_you_want']
fputcsv($fp1, $row);
}
While using select query itself you can concat $ symbol. Like below
$query = $db->query("SELECT concat('$',Net_Income) as Net_Income FROM clientsdata WHERE Client_Id = '".$userID."'");
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
fputcsv($fp1, $row);
}

php fputscv not creating csv file instead showing output on same page

On my local machine it is working fine. but on server it is printing the output on the same page instead of creating of a CSV file. can anyone help
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=memberList.csv');
ob_end_clean();
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('First Name', 'Last Nameenter code here', 'Street Name', 'City', 'State', 'Zip Code'));
// fetch the data
$csvQry = "SELECT * from tabel where num=1";
if ($_POST['stateList']!='all'){
$csvQry = "SELECT * from table";
}
$csvRows = mysqli_query($db,$csvQry);
// loop over the rows, outputting them
while ($csvRow = mysqli_fetch_assoc($csvRows)) {
fputcsv($output, $csvRow);
}
fclose($output);

Categories