Instead of saving CSV file how to Download the file - php

I am exporting data from a database using CSV extension and I want to download the results as a CSV file. How can I do that?
This is my code:
public function actionExportexcel() {
$con = mysql_connect("localhost", "root", "") or die();
mysql_select_db("fiducial", $con);
$filename = 'uploads/'.strtotime("now").".csv";
$query = mysql_query("SELECT * FROM
(
SELECT employeecode,name,dob,age,sex,employee_relation,company_id
FROM employeedetails
UNION
SELECT employeecode,father_name,father_dob,father_age,father_gender,father_relation,company_id
FROM employeedetails
WHERE father_name IS NOT NULL AND company_id IS NOT NULL
UNION
SELECT employeecode,mother_name,mother_dob,mother_age,mother_gender,mother_relation,company_id
FROM employeedetails
WHERE mother_name IS NOT NULL AND mother_dob IS NOT NULL
)t WHERE t.company_id = '56' ORDER by t.employeecode ") or die(mysql_error());
$num_rows = mysql_num_rows($query);
if($num_rows >= 1)
{
$rows = mysql_fetch_assoc($query);
$seperator = "";
$comma = "";
foreach ($rows as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $name);
$comma = ",";
}
$seperator .= "\n";
$fp = fopen($filename, "w");
fputs($fp, $seperator);
mysql_data_seek($query, 0);
while($rows = mysql_fetch_assoc($query))
{
$seperator = "";
$comma = "";
foreach ($rows as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $value);
$comma = ",";
}
$seperator .= "\n";
fputs($fp, $seperator);
}
echo "Data successfully exported";
fclose($fp);
} else {
echo "No data is Available";
}
}
How can I download it as a CSV file?

You need to set the HTTP headers correctly for a CSV file download and then instead of writing your query results to a CSV file on the local server, you need to write it to the PHP output buffer (php://output):
Full working example:
public function actionExportexcel() {
$con = mysql_connect("localhost", "root", "") or die();
mysql_select_db("fiducial", $con);
$filename = 'uploads/'.strtotime("now").".csv";
$query = mysql_query("SELECT * FROM
(
SELECT employeecode,name,dob,age,sex,employee_relation,company_id
FROM employeedetails
UNION
SELECT employeecode,father_name,father_dob,father_age,father_gender,father_relation,company_id
FROM employeedetails
WHERE father_name IS NOT NULL AND company_id IS NOT NULL
UNION
SELECT employeecode,mother_name,mother_dob,mother_age,mother_gender,mother_relation,company_id
FROM employeedetails
WHERE mother_name IS NOT NULL AND mother_dob IS NOT NULL
)t WHERE t.company_id = '56' ORDER by t.employeecode ") or die(mysql_error());
$num_rows = mysql_num_rows($query);
if($num_rows >= 1) {
header('Content-Description: Your Download Name ');
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=yourfilename.csv');
$rows = mysql_fetch_assoc($query);
$seperator = "";
$comma = "";
foreach ($rows as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $name);
$comma = ",";
}
$seperator .= "\n";
$fp = fopen('php://output', 'w');
fputs($fp, $seperator);
mysql_data_seek($query, 0);
while($rows = mysql_fetch_assoc($query))
{
$seperator = "";
$comma = "";
foreach ($rows as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $value);
$comma = ",";
}
$seperator .= "\n";
fputs($fp, $seperator);
}
fclose($fp);
} else {
echo "No data is Available";
}
}

Use
header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename=<filename>.csv');

Related

download csv but rows with comma is blank

guys i got this codes that does work but some rows in database which has values with , commas those rows gets downloaded blank. what is the fix for this?
here is my php
<?php
require_once('config.php');
$y = $_REQUEST['y'];
$m = $_REQUEST['m'];
$date = "$y-$m";
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=Data-Backup-' . $date . '.csv');
$select_table = mysql_query("SELECT * FROM records WHERE DATE_FORMAT(data_submitted, '%Y-%m') = '$date' ORDER BY ID DESC");
$rows = mysql_fetch_assoc($select_table);
if ($rows) {
getcsv(array_keys($rows));
}
while ($rows) {
getcsv($rows);
$rows = mysql_fetch_assoc($select_table);
}
function getcsv($no_of_field_names)
{
$separate = '';
foreach ($no_of_field_names as $field_name) {
if (preg_match('/\\r|\\n|,|"/', $field_name)) {
$field_name = '' . str_replace('', $field_name) . '';
}
echo $separate . $field_name;
$separate = ',';
}
echo "\r\n";
}
?>
You can use fputcsv.
$output = fopen('php://output', 'w');
$count = 0;
while($row = mysql_fetch_assoc($select_table)) {
if ($count == 0) {
// header
fputcsv($output, array_keys($row));
}
fputcsv($output, array_values($row));
$count++;
}
fpassthru($output);

Need Help on Export SQL to CSV through PHP

I have this PHP script which is supposed to take an SQL Query and output it to a CSV file, I know that when I run it i'm getting the right Statement put in but it does not seem to generate a file to my uploads folder.
Could anyone debug this for me?
<?php
function ExportExcel($statement)
{
$filename = "uploads/".strtotime("now").'.csv';
$sql = mysql_query("$statement") or die(mysql_error());
$num_rows = mysql_num_rows($sql);
if($num_rows >= 1)
{
$row = mysql_fetch_assoc($sql);
$fp = fopen($filename, "w");
$seperator = "";
$comma = "";
foreach ($row as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $name);
$comma = ",";
}
$seperator .= "\n";
fputs($fp, $seperator);
mysql_data_seek($sql, 0);
while($row = mysql_fetch_assoc($sql))
{
$seperator = "";
$comma = "";
foreach ($row as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $value);
$comma = ",";
}
$seperator .= "\n";
fputs($fp, $seperator);
}
fclose($fp);
echo "<a href='$filename'>Download</a>";
echo $statement;
}
else
{
echo "error";
}
}
?>
If someone has a similar script that uses mysqli that would be nice
here is a example of a export script I use on my apps using MySqli. This will get you started...
<?php
function ExportExcel($statement){
$output = "";
$sql = mysqli_query($db , $statement);
$columns_total = mysqli_num_fields($sql);
// Get The Field Name
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysqli_fetch_field_direct($sql, $i);
$output .= '"'.$heading->name.'",';
}
$output .="\n";
// Get Records from the table
while ($row = mysqli_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}
// Download the file
$filename = "CSV_NAME_GOES_HERE.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
exit;
}
?>

Getting multi records from check boxes

First of all before anyone here regrets and set this duplicate I don't know will be or not but I tried to search alot but wasn't able to find my answer I created a table from which there are some checkboxes what I want to do is if someone selects 3 entries then the data will be exported for those 3 entries only this is y query what I have done so far
$id = $_POST['select'];
foreach($id as $key) {
echo $key . ", ";
}
$sql = mysqli_query($con, "SELECT * FROM $table WHERE uid IN ('$key')") or die(mysqli_error($con));
$num_rows = mysqli_num_rows($sql);
I dont know why it's giving me the last record only ? it should have given me 3 records like happens in between query it give us the entries of d between 1 and 3 but what if we select id 1 3 5 it shoulld have given these 3 right so for exporting it to excel i did this code found some help working fine but having issue with my query not successful
if($num_rows >= 1)
{
$row = mysqli_fetch_assoc($sql);
$fp = fopen($filename, "w");
$seperator = "";
$comma = "";
foreach ($row as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $name);
$comma = ",";
}
$seperator .= "\n";
fputs($fp, $seperator);
mysqli_data_seek($sql, 0);
while($row = mysqli_fetch_assoc($sql))
{
$seperator = "";
$comma = "";
foreach ($row as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $value);
$comma = ",";
}
$seperator .= "\n";
fputs($fp, $seperator);
}
fclose($fp);
echo "Your file is ready. You can download it from <a href='$filename'>here!</a>";
}
else
{
echo "There is no record in your Database";
}
$key is only going to be the last value in the foreach. Give the following a go:
$id = $_POST['select'];
$key = "";
foreach($id as $vals) {
$key = $key . $vals . ",";
}
$key = trim($key, ",");
$sql = mysqli_query($con, "SELECT * FROM $table WHERE uid IN ('$key')") or die(mysqli_error($con));

Exporting to CSV from MySQL via PHP

I am trying to bug fix a PHP script that should export values from a MySQL database to a CSV file.
The PHP file is returning a blank CSV file & I can't figure out why & I've been stuck on this for quite a while, so any help would be much apprwciated.
Code below:
<?
include('../../../inc/config.php');
$period = $_GET['pid'];
$psql = "SELECT month, year FROM survey_period WHERE sid = " . $period;
$pres = mysql_query($psql, $dcon);
$prow = mysql_fetch_array($pres);
$pmonth = $prow['month'];
$pyear = $prow['year'];
$query="SELECT
sid,
date,
stove_id,
name,
gender,
marital_status,
occupation_of_household,
cz_stove AS km_stove,
happy_with_cz_stove AS happy_with_km_stove,
cz_stove_in_use AS km_stove_in_use,
know_how_to_use,
FROM survey_usage WHERE period = " . $_GET['pid'];
$result = mysql_query($query, $dcon);
//header('Content-Disposition: attachment;filename=export.csv');
$filename = 'usage-'.$pid.'-'.$pmonth.'-'.$pyear;
header('Content-Type: text/csv');
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
$row = mysql_fetch_assoc($result);
if ($row) {
echocsv(array($title));
echo "\r\n";
echocsv(array_keys($row));
}
while ($row) {
echocsv($row);
$row = mysql_fetch_assoc($result);
}
function echocsv($fields)
{
$separator = '';
foreach ($fields as $field) {
if (preg_match('/\\r|\\n|,|"/', $field)) {
$field = '"' . str_replace('"', '""', $field) . '"';
}
echo $separator . $field;
$separator = ',';
}
echo "\r\n";
}
?>
hey i have a code you can use it like this
<?PHP
// Define database connection variable dynamically
$DB_Server = "localhost"; //MySQL Server
$DB_Username = "root"; //MySQL Username
$DB_Password = ""; //MySQL Password
$DB_DBName = "test1"; //MySQL Database Name
$DB_TBLName = "tabletest"; //MySQL Table Name
$filename = "excelfilename"; //File Name
//create MySQL connection
$sql = "Select * from csvtable";
$Connect = #mysqli_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:<br>" . mysqli_error() );
//select database
$Db = #mysqli_select_db( $Connect,$DB_DBName) or die("Couldn't select database:<br>" . mysqli_error() );
//execute query
$result = #mysqli_query( $Connect,$sql) or die("Couldn't execute query:<br>" . mysqli_error() );
function cleanData(&$str)
{
if ($str == 't')
$str = 'TRUE';
if ($str == 'f')
$str = 'FALSE';
if (preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
$str = "'$str";
}
if (strstr($str, '"'))
$str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "file_" . date('Ymd') . ".csv";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: text/csv;");
$out = fopen("php://output", 'w');
$flag = false;
while ($row = mysqli_fetch_assoc($result))
{
if (!$flag)
{
// display field/column names as first row
fputcsv($out, array_keys($row), ',', '"'); $flag = true;
}
array_walk($row, 'cleanData');
// insert data into database from here
fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
exit;
//end
?>
The issue is that you are not writing anything to the csv file before opening it.
Use this code
$fp = fopen($filename, 'w');
$result = mysql_query($query);
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++) {
$headers[] = mysql_field_name($result , $i);
}
fputcsv($fp, $headers);
while($row = mysql_fetch_assoc($result)) {
fputcsv($fp, $row);
}
fclose($fp);
header('Content-Type: text/csv');
header( "Content-disposition: filename=".$filename);
readfile($filename);
Thanks to everyone for your suggestions, problem now solved, turned out to be a simple comma in the wrong place - "know_how_to_use," changed to " know_how_to_use" solved the problem. Thanks #Tintu C Raju for pointing me in the right direction

excel automatically open file after downloading in php

below is my codes for my excel. its functioning except for one thing. i don't see if my file is already save to excel.. can you help me how to automatically open my file after i download it.. i think something is missing or wrong in my codes.. so please. help . thanks.
{
$conn = mysql_connect("localhost","root","") or die (mysql_error());
mysql_select_db("copylandia",$conn);
//$fp = fopen($filename,"w+");
$filename = 'attachment'. date('Y-m-d') .'.csv';
$fp = fopen($filename,"w+");
$sql = mysql_query("select * from user") or die (mysql_error());
$num_rows = mysql_num_rows($sql);
if($num_rows >= 1)
{
$row = mysql_fetch_assoc($sql);
$fp = fopen($filename,"w+");
$seperator = "";
$comma = "";
foreach($row as $name => $value)
{
$seperator .= $comma .'' . str_replace('','""',$name);
$comma = ",";
}
$seperator .= "\n";
//echo $seperator;
fputs($fp,$seperator);
mysql_data_seek($sql, 0);
while($row = mysql_fetch_assoc($sql))
{
$seperator = "";
$comma = "";
foreach($row as $name => $value)
{
$seperator .= $comma .'' . str_replace('','""',$value);
$comma = ",";
}
$seperator .= "\n";
fputs($fp,$seperator);
}
fclose($fp);
}
else
{
echo 'No records in the database!';
}
}
You can't force the browser/computer to open a file after download. The user must make that decision.
Although, since you are trying to make a CSV file, I will at least make a suggestion to help you out instead of crushing your dreams by telling you you can't do this:
Try fputcsv() instead of trying to make the string yourself:
I'm really cool! Click me!

Categories