How to add title in csv download from mysql database - php

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
}

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

Export PHP Variable Results To CSV

I am using php to run a SQL Query and populate a HTML Table. My question is, since I have the $query variable house the sql results, would it be possible to add a button to "Export To CSV" and if the button is clicked it will export a .csv file of the $query that is formatted the same way that the html table that is generated?
Say the query string is like this:
$query .= "Select red, green, blue from colorsDB where signoff is not null";
$db->setQuery($query);
$query = $db->loadObjectList();
You can try this way
$result = mysql_query('SELECT * FROM `some_table`');
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result)
{
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
die;
}

PHP - blank row when saving array as CSV

Im trying to save my sql query as csv using php. Everything goes well except there is a blank row in the beginning of the csv file. How can I remove the blank row at the beginning? Here is my code:
include('connectdb.php');
mysqli_error($mysqli));
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="online_applicants.csv"');
header('Pragma: no-cache');
header('Expires: 0');
$file = fopen('php://output', 'w');
$sql = "select Firstname from applicant";
$result = mysqli_query($mysqli, $sql) or die("selection error " .
mysqli_error($mysqli));
while($row = mysqli_fetch_assoc($result))
{
fputcsv($file, $row);
}
fclose($file);
Thanks!
Before saving the row, you can try to check if the row is blank, example:
while($row = mysqli_fetch_assoc($result))
{
if ($row != "") {
fputcsv($file, $row);
}
}
Or you can check the size, usually the "blank" row may have something, but the size will be less than a normal row, example:
while($row = mysqli_fetch_assoc($result))
{
if (strlen($row) > 5) { // if the row has more than 5 characters, put in the file
fputcsv($file, $row);
}
}

Export a CSV File for a 'username' in 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);
}

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

Categories