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);
}
Related
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);
}
?>
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);
}
?>
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/
Getting a blank screen with no errors and no code. I have php version 5.3.10 on my live server but the code was developed on a local computer with version 5.6.2. The code written below was written for latest version of PHP but the live server the page will sit on has the old version 5.3.10.
I need to know which PHP syntax below is new and needs to be backwards compatible.
// Triggered when the Export CSV button is clicked.
if(isset($_POST["search_results"]) && isset($_POST["pub_results"]) ) {
// Sets the value of the hidden field as a variable (the value will be the SQL query saved earlier)
$results = $_POST['search_results'];
$pubResults = $_POST['pub_results'];
$query = $pubResults;
// Performs the query again to get the results to export
$r = mysqli_query($conn, $query)or die(mysql_error());
if (!mysqli_num_rows($r)==0) {
// Adds all of the results to the CSV file
while ($row = mysqli_fetch_array($r)) {
$pnfn = ucwords(strtolower($row[1]));
$dataRow = [$row[0], $row[1], $row[2]];
}
$pnfn = preg_replace('/\s+/', '', $pnfn);
$filename = $pnfn . "-" . $timestamp . ".csv";
// Set headers for the CSV file
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=" . $filename);
$csvHeader[] = "Pub Information:";
fputcsv($fp, $csvHeader);
$pubHeader = ["Outlet Code", "Pub Short Address", "Regional Code"];
fputcsv($fp, $pubHeader);
fputcsv($fp, $dataRow);
}
$csvHeader2[] = "Points Of Interest:";
fputcsv($fp, $csvHeader2);
// Query to retrieve all of the column names in the Entertainment table (are the same for the other 3) so that
// they can appear at the top of the CSV file.
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='enterprisepoi_342' AND TABLE_NAME='poi'";
$r = mysqli_query($conn, $query)or die(mysql_error());
// Adds the column names to an array
while ($row = mysqli_fetch_array($r)) {
$header[] = $row[0];
}
array_push($header, "Distance");
fputcsv($fp, $header);
$query = $results;
// Performs the query again to get the results to export
$r = mysqli_query($conn, $query)or die(mysql_error());
if (!mysqli_num_rows($r)==0) {
// Adds all of the results to the CSV file
while ($row = mysqli_fetch_array($r)) {
$distance = number_format($row["distance"], 2, ".", "");
$dataRow = [$row[0], $row[1], $row[2], $row[3], $row[4], $row[5], $row[6], $distance];
fputcsv($fp, $dataRow);
}
// Exit so that the rest of the HTML in the document does not appear in the
// CSV file.
exit;
}
}
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);