Export a CSV File for a 'username' in PHP - php

I have data in a MySQL database. I am sending the participant a URL to get their data out as a CSV file. How can I, when they click the link, ...
A download link is there to download all data from the database in csv format.
<?php
$insquery = "SELECT username FROM r_institution where status=1";
$exportstmt = $conn->query($insquery);
$insresults = mysqli_fetch_assoc($exportstmt);
foreach ($insresults as $rs) {
$row = array();
$row[] = stripslashes($rs["username"]);
$content[] = $row;
}
$content = array();
$title = array("username");
foreach ($insresults as $rs) {
$row = array();
$row[] = stripslashes($rs["username"]);
$content[] = $row;
}
$output = fopen('php://output', 'w');
fputcsv($output, $title);
foreach ($content as $con) {
fputcsv($output, $con);
}
?>

$filename = "testing-exports.csv";
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
$insquery = "SELECT username FROM r_institution where status=1";
//$exportstmt = $conn->query($insquery);
$insresults = $conn->query($insquery);
//$insresults = mysqli_fetch_assoc($exportstmt);
foreach ($insresults as $rs) {
$row = array();
$row[] = stripslashes($rs["username"]);
$content[] = $row;
}
$content = array();
$title = array("Institution Emails");
foreach ($insresults as $rs) {
$row = array();
$row[] = stripslashes($rs["username"]);
$content[] = $row;
}
$output = fopen('php://output', 'w');
fputcsv($output, $title);
foreach ($content as $con) {
fputcsv($output, $con);
}

Related

Not able to export CSV file from MySQL data by using following code

When I click on button to export file it just redirects to the
export.php file given as href to the button and does nt download the
file
<?php
include 'config.php';
$query = "SELECT d_domain, d_purchase_price, d_selling_price FROM
domains";
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result) > 0) {
$delimiter = ",";
$filename = "data.csv";
$output = fopen('php://memory', 'w');
$fields = array('Domain Name', 'Purchase Price', 'Selling Price');
fputcsv($output, $fields, $delimiter);
while ($row = mysqli_fetch_assoc($result)) {
$lineData = array($row['d_domain'], $row['d_purchase_price'],
$row['d_selling_price']);
fputcsv($output, $lineData, $delimiter);
}
fseek($output, 0);
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename= data.csv');
fpassthru($f);
}
Use rewind before seek also in fpassthru($f) you're passing wrong file handle
Try this code
<?php
include 'config.php';
$query = "SELECT d_domain, d_purchase_price, d_selling_price FROM
domains";
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result) > 0) {
$delimiter = ",";
$filename = "data.csv";
$output = fopen('php://memory', 'w');
$fields = array('Domain Name', 'Purchase Price', 'Selling Price');
fputcsv($output, $fields, $delimiter);
while ($row = mysqli_fetch_assoc($result)) {
$lineData = array($row['d_domain'], $row['d_purchase_price'],
$row['d_selling_price']);
fputcsv($output, $lineData, $delimiter);
}
rewind($output);
fseek($output, 0);
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename= data.csv');
fpassthru($output); // You're using $f
}
If it still not working then might be some issue with the php://memory usage in your server.. might be it will restricted.. You can also try with php://output this will definitely work
Try this code
<?php
include 'config.php';
$query = "SELECT d_domain, d_purchase_price, d_selling_price FROM
domains";
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result) > 0) {
$delimiter = ",";
$filename = "data.csv";
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename= data.csv');
$output = fopen('php://output', 'w');
$fields = array('Domain Name', 'Purchase Price', 'Selling Price');
fputcsv($output, $fields, $delimiter);
while ($row = mysqli_fetch_assoc($result)) {
$lineData = array($row['d_domain'], $row['d_purchase_price'],
$row['d_selling_price']);
fputcsv($output, $lineData, $delimiter);
}
//rewind($output);
//fseek($output, 0);
//fpassthru($output); // You're using $f
fclose($output);
}

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

while exporting file from database to csv,it gives displays content in the row of table column name

While exporting file to csv,my contents are added in the same row of column names.I want content just below to the respective columns.The code is as follow
<?php
$filename = "file.csv";
$fp = fopen('php://output', 'w');
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
$headerLine = 'Sr. No,Name,DOB,Address';
fwrite($fp, $headerLine);
$query = "select * from registratin";
$result = mssql_query($query);
$i = 1;
while($row = mssql_fetch_row($result)) {
$row = array_merge(array($i), $row);
fputcsv($fp, $row);
$i++;
}
?>
You can do it simply as follows , there is no need to array merge
<?php
$filename = "file.csv";
$fp = fopen('php://output', 'w');
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
$headerLine = 'Sr. No,Name,DOB,Address';
fputcsv($fp, explode(",",$headerLine); // adding heading
$query = "select * from registratin";
$result = mssql_query($query);
$i = 1;
while($row = mssql_fetch_row($result)) {
//$row = array_merge(array($i), $row); ***no need***
fputcsv($fp, $row);
$i++;
}
fclose($fp);
?>
Its better to use mysqli, and this is the simple way to get the work done.
And in select choose only required columns.
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen('php://output', 'w');
fputcsv($output, array('SR No', 'Name','DOB','Address'));
$conn = mysqli_connect('localhost', 'root', 'password',"database");
$rows = mysqli_query($conn,'SELECT * from registration');
while ($row = mysqli_fetch_assoc($rows))
fputcsv($output, $row);

Download data through mysql

// Database Connection
$host="localhost";
$uname="root";
$pass="";
$database = "xyz";
$connection=mysql_connect($host,$uname,$pass);
echo mysql_error();
//or die("Database Connection Failed");
$selectdb=mysql_select_db($database) or die("Database could not be selected");
$result=mysql_select_db($database)
or die("database cannot be selected <br>");
// Fetch Record from Database
$output = "";
$table = ""; // Enter Your Table Name
$sql = mysql_query("select * from $table");
$columns_total = mysql_num_fields($sql);
// Get The Field Name
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\n";
// Get Records from the table
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}
// Download the file
$filename = "myFile.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
exit;
Create a connection and use following code for CSV generation in PHP.
$result = mysqli_query ($mysqliConn,"SELECT * FROM core ORDER BY start_datetime ASC");
$fields = mysqli_fetch_fields($result);
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysqli_fetch_fields($result);
$headers = array();
foreach ($fields as $field) {
$headers[] = $field->name;
}
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="core.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
Hope this helps.

How to add title in csv download from mysql database

My csv download code run correctly but i want to add title in first row of csv.But I can't.
My code
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
include('config.php');
$sql ="select county.title,beach.beach_name,beach.notice,beach.latitude,beach.longitude,beach.rainfall,beach.temperature,beach.status_id from beach as beach,county as county where beach.county_id=county.id ";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc( $result)) {
$data[] = $row; // Inside while loop
}
outputCSV($data);
function outputCSV($data) {
$output = fopen("php://output", "w");
foreach ($data as $rowc) {
fputcsv($output, $rowc);
}
fclose($output);
}
Create an array before dumping data into that array, like below:
$sql ="select county.title,beach.beach_name,beach.notice,beach.latitude,beach.longitude,beach.rainfall,beach.temperature,beach.status_id from beach as beach,county as county where beach.county_id=county.id ";
$data[] = array("title","Beach Name","Notice","Latitue","Longitude","RainFall","Temperature","Satus ID");
$result = mysql_query($sql);
while( $row = mysql_fetch_assoc( $result)){
$data[] = $row; // Inside while loop
}

Categories