Generating a CSV download using PDO queries - php

I am trying to make a user able to download a CSV backup of all of their data on my server.
This means i am trying to execute multiple query's and placing the results into a CSV file.
This is what i have so far:
<?php
// Connect
include 'config.php'; // Config contains PDO database connection, etc.
// Generate filename
$filename = $_SESSION['current_group'].'-'.date('d.m.Y').'.csv';
// Get backup data from MYSQL database
$result_users = $conn->prepare('SELECT `user_name`, `user_email` FROM `users` WHERE `group_id` = ?');
$result_users->execute(array($_SESSION['current_group_id']));
$result_items = $conn->prepare('SELECT `item_name`, `item_value`, `item_group` FROM `items` WHERE `group_id` = ?');
$result_items->execute(array($_SESSION['current_group_id']));
# Create array
$list = array ("## START OF USER TABLE ##");
// Append results to array
while ($row = $result_users->fetch(PDO::FETCH_ASSOC)) {
array_push($list, array_values($row));
}
array_push($list,"## END OF USER TABLE ##");
array_push($list,"## START OF ITEMS TABLE ##");
while ($row = $result_items->fetch(PDO::FETCH_ASSOC)) {
array_push($list, array_values($row));
}
array_push($list,"## END OF ITEMS TABLE ##");
// Output array into CSV file
$fp = fopen('php://output', 'w');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="'.$filename.'"');
foreach ($list as $ferow) {
fputcsv($fp, split(',',$ferow));
}
?>
The expected output is supposed to be something like:
## START OF USERS TABLE ##
"John","john#email.com"
"James","james#email.com"
## END OF USERS TABLE ##
## START OF ITEMS TABLE ##
"Soap","A lot","Household"
"Banana","2","Food"
## END OF ITEMS TABLE ##
etc.
The problem is that the valued do not correctly get pushed into the $list array.
What should i do in order to get the wanted result?
Thanks!

I think that your code its a little complicated for what you need. I don't test this code but probably works
$sql = "SELECT user_name, user_email FROM users WHERE group_id = :group_id
UNION
SELECT item_name, item_value, item_group FROM items WHERE group_id = :group_id
";
$sth = $conn->prepare($sql);
$sth->bindValue(':group_id', $_SESSION['current_group_id'], PDO::PARAM_INT);
$sth->execute();
$filename = $_SESSION['current_group'].'-'.date('d.m.Y').'.csv';
$data = fopen($filename, 'w');
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
fputcsv($data, $row);
}
fclose($data);

I solved it by doing the following:
// Create array
$list = array ();
// Append results to array
array_push($list, array("## START OF USER TABLE ##"));
while ($row = $result_users->fetch(PDO::FETCH_ASSOC)) {
array_push($list, array_values($row));
}
array_push($list, array("## END OF USER TABLE ##"));
// Output array into CSV file
$fp = fopen('php://output', 'w');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="'.$filename.'"');
foreach ($list as $ferow) {
fputcsv($fp, $ferow);
}

Related

Export data to CSV file with php and simple html dom

How to export grabbed data to .csv file? I'm using php simple html dom to parse data. Here is the code:
foreach ($linkoviStranica as $stranica)
{
$podaciStranice = "http://someurl/$stranica";
$data = file_get_html($podaciStranice);
$name = $data->find('div[class="price-card-name-header-name"]');
$onlinePrice = $data->find('div[class="price-box online"]');
$diffPrice = $data->find('div[class="price-box paper"]');
echo "<strong>".$name[0]->innertext."<strong>"."<br>";
if (!empty($onlinePrice[0]->innertext))
{
echo $onlinePrice[0]->innertext."<br>";
}
if (!empty($diffPrice[0]->innertext))
{
echo $diffPrice[0]->innertext."<br>";
echo "---------------------"."<br>";
}
}
I want to export, $name, $onlinePrice, $diffPrice to csv file with header in the following format:
name onlinePrice diffPrice
example 10 44
xxxx 412 461
zzzzz 1414 41
Could you please help me? Thanks!
Something like this:
// Define a array to hold all the data
$data = [];
// OR use this line if you want the headers with names on the first line of the file
// $data = [['name', 'onlinePrice', 'diffPrice']];
// Loop the raw data
foreach ($linkoviStranica as $stranica) {
$podaciStranice = "http://someurl/$stranica";
$data = file_get_html($podaciStranice);
$name = $data->find('div[class="price-card-name-header-name"]');
$onlinePrice = $data->find('div[class="price-box online"]');
$diffPrice = $data->find('div[class="price-box paper"]');
// Add current row to out array
$data[] = [
$name[0]->innertext,
$onlinePrice[0]->innertext,
$diffPrice[0]->innertext
];
}
// Open a new file. Replace the file name with the name you'd like
$fp = fopen('file.csv', 'w');
// Loop each row in the data array
foreach ($data as $fields) {
// This method converts a row to a CSV line (http://php.net/manual/en/function.fputcsv.php)
fputcsv($fp, $fields);
}
// Close the file handler
fclose($fp);
$header ="SNo , Order Date , Order Number , Compaign , Amount , Order Status , Used Date , Cancel Reason , Order Commision , Payment Date , Payment Status \n";
$header1 =$header ;
$result='';
foreach ($data as $fields) {
$result= 'echo your data with coma seprated '."\n";
}
$all=$header.$result;
$name="report.csv";
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=".$name);
header("Pragma: no-cache");
header("Expires: 0");
print "$header1 $result";

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);
}

Output to CSV generating errors

I don't have a lot of experience with using the fputcsv function.
I'm trying to make a function, by which an admin can download a file with all the user information.
The CSV should be generated in this way :
Serial Number Username Email etc etc
And then the records from a query.
I have this function which I'm using to generate the csv file :
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
// open raw memory as file so no temp files needed, you might run out of memory though
$f = fopen('php://memory', 'w');
// loop over the input array
foreach ($array as $line) {
// generate csv lines from the inner arrays
fputcsv($f, $line, $delimiter);
}
// rewrind the "file" with the csv lines
fseek($f, 0);
// tell the browser it's going to be a csv file
header('Content-Type: application/csv');
// tell the browser we want to save it instead of displaying it
header('Content-Disposition: attachement; filename="'.$filename.'";');
// make php send the generated csv lines to the browser
fpassthru($f);
}
And then I call the function:
<?php
include 'inc/inc.functions.php';
include 'dbconnector.php';
$query="SELECT * from users order by email LIMIT 0,30";
$result=mysql_query($query,$db) or die(mysql_error($db));
$array=mysql_fetch_array($result);
foreach($array as $arr)
{
array_to_csv_download($arr,"records.csv",":");
}
?>
The CSV generated displays: Warning, Invalid argument supplied for foreach.
What should I do to display in the way I require?
UPDATE
http://i.imgur.com/2xH0gT1.png
You're currently calling your function for a single row in the database, rather than for the entire result set. The following should use your function correctly:
$query = "SELECT * from users order by email LIMIT 0,30";
$result = mysql_query($query,$db) or die(mysql_error($db));
$array = array();
# Headers
$array[] = array("Serial Number","Username","Email","etc etc");
while($row = mysql_fetch_row($result)) {
$array[] = $row;
}
array_to_csv_download($array,"records.csv",":");

send an email exported cvs file php mysql

I am trying to send email exported csv file. However, when i click the link, have a pop-up to download a CVS with the record from MySQL. how can i send an email this csv file to spesific email adress ? thanks a lot for help and ideas.
best regards.
Here is my code
header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename=log.csv");
header("Pragma: no-cache");
header("Expires: 0");
$resultstr = array();
foreach ($selectionlist as $result)
$resultstr[] = $result;
$ww=implode(",",$resultstr);
function escape_csv_value($value) {
$value = str_replace('"', '""', $value); // First off escape all " and make them ""
if(preg_match('/,/', $value) or preg_match("/\n/", $value) or preg_match('/"/', $value)) { // Check if I have any commas or new lines
return '"'.$value.'"'; // If I have new lines or commas escape them
} else {
return $value; // If no new lines or commas just return the value
}
}
$sql = mysql_query("SELECT * FROM article
WHERE idArticle in ($ww) ORDER BY idArticle DESC"); // Start our query of the database
$numberFields = mysql_num_fields($sql) or die('MySql Error' . mysql_error());; // Find out how many fields we are fetching
if($numberFields) { // Check if we need to output anything
for($i=0; $i<$numberFields; $i++) {
$keys[] = mysql_field_name($sql, $i); // Create array of the names for the loop of data below
$col_head[] = escape_csv_value(mysql_field_name($sql, $i)); // Create and escape the headers for each column, this is the field name in the database
}
$col_headers = join(',', $col_head)."\n"; // Make our first row in the CSV
$data = '';
while($info = mysql_fetch_object($sql)) {
foreach($keys as $fieldName) { // Loop through the array of headers as we fetch the data
$row[] = escape_csv_value($info->$fieldName);
} // End loop
$data .= join(',', $row)."\n"; // Create a new row of data and append it to the last row
$row = ''; // Clear the contents of the $row variable to start a new row
}
// Start our output of the CSV
/*header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename=log.csv");
header("Pragma: no-cache");
header("Expires: 0");*/
echo $col_headers.$data;
} else {
// Nothing needed to be output. Put an error message here or something.
echo 'No data available for this CSV.';
}
OK. First you have to Save the CSV file. If you set headers as you mentioned the file will be automatically downloaded. Please read this article on this.
http://us2.php.net/manual/en/function.fputcsv.php
Once you create your CSV file you can email it using PHP mail function. If you need some library just check this out. It's easy to implement.
http://www.redvodkajelly.com/code/php-email-class/

Categories