Create comma delimited .csv file with php - php

I am trying to:
create comma delimited .csv file with php code.
Insert column name in the first line of the .csv file.
Please advise how can I make this happen.
<?php
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=".$batch_id.".csv");
header("Pragma: no-cache");
header("Expires: 0");
$conn_sp = mssql_connect("SQLServer", "user", "password");
$db_sp = mssql_select_db("databaseName", $conn_sp);
$stmt = mssql_init("[StoredProcedureName]",$conn_sp);
mssql_bind($stmt, "#BatchNo", $batch_id, SQLVARCHAR, FALSE, FALSE, 20);
$result = mssql_query("SET ANSI_NULLS ON");
$result = mssql_query("SET ANSI_WARNINGS ON");
$result = mssql_execute($stmt);
$record="";
$comma=",";
$record_end="\n";
while ($row = mssql_fetch_array($result, MSSQL_ASSOC)){
foreach ($row as $key => $value) {
echo $value;
}
echo "\n";
}?>
!

Well just look at how a .csv-file is created.
Usually like this:
Delimiter: ,
New line: \n
Enclose entry by: "
e.g.
"r1a","r1b","r1c"
"r2a","r2b","r2c"
etc...
This is how your code should work (untested):
echo '"colname1","colname2",...';
while ($row = mssql_fetch_array($result, MSSQL_ASSOC)){
$first = true;
foreach ($row as $key => $value) {
if(!$first) {
echo ",";
}
echo '"'.$value.'"';
}
echo "\n";
$first=false;
}

Related

Is it possible to export the results of a search into a excel document?

I have a functioning search bar and a functioning excel writer but I'm unaware on what query I would use to export results from a search that has been made. Is this possible?
The code that I've got for the search bar is:
<?php
include ('database_conn.php');
$output = '';
if(isset($_POST['search'])) {
$search = $_POST['search'];
$search = preg_replace("#[^0-9a-z]i#","", $search);
$query = mysqli_query($conn, "SELECT * FROM attendance WHERE stud_id LIKE '%$search%'") or die ("Could not search");
$count = mysqli_num_rows($query);
if($count == 0){
$output = "There was no search results!";
}else{
while ($row = mysqli_fetch_array($query)) {
$stud_id = $row ['stud_id'];
$module = $row ['module'];
$attendance_status = $row ['attendance_status'];
$output .='<div> '.$stud_id.' '.$module.' '.$attendance_status.'</div>';
}
}
}
?>
and then the code that I have for the excel writer is: (database connection is already on)
$output = '';
if(isset($_POST["export"]))
{
$result=mysqli_query($conn, "SELECT * FROM attendance ");
if(mysqli_num_rows($result) > 0)
{
$output .= '
<table class="table" bordered="1">
<tr>
<th>Name</th>
<th>Module</th>
<th>Status</th>
<th>Date</th>
</tr>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["stud_id"].'</td>
<td>'.$row["module"].'</td>
<td>'.$row["attendance_status"].'</td>
<td>'.$row["date"].'</td>
</tr>
';
}
$output .= '</table>';
header('Content-Type: application/xls');
header('Content-Disposition: attachment; filename=download.xls');
echo $output;
}
}
?>
I'm aware at the moment that my export button will just export everything from the attendance table, I'm not sure which query I would use to make it export the search results.
Instead of a custom class, I recommend using PhpSpreadsheet (the successor of PHPExcel). It allows you to add formatting, font styles, save as XLSX, etc.
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');
$writer = new Xlsx($spreadsheet);
$writer->save('hello world.xlsx');
Otherwise create a CSV string, set the content headers to write a XLS file, and Excel will read it just fine. E.g.
function export_excel_csv() {
$conn = mysql_connect("localhost","root","");
$db = mysql_select_db("database",$conn);
$rec = mysql_query("SELECT * FROM table") or die (mysql_error());
$num_fields = mysql_num_fields($rec);
for($i = 0; $i < $num_fields; $i++ )
$header .= mysql_field_name($rec,$i)."\\t";
while($row = mysql_fetch_row($rec)) {
$line = '';
foreach($row as $value) {
if((!isset($value)) || ($value == "")) {
$value = "\\t";
}
else {
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\\n";
}
$data = str_replace("\\r" , "" , $data);
if ($data == "")
$data = "\\n No Record Found!\n";
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=reports.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\\n$data";
}
Regarding your question about the header type, check this post and try:
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filename.'.xls"');

PHP Export to CSV does not send all data to the file

I am exporting to CSV from my php reporting website. I have reports that are more than 80k rows. When I export one of them the whole data set does not get exported. I have tried several times with a report that is 88k+ rows and it exports 87k+ rows and then stops part way through the last row that is exported.
What is going on? The query that pulls the data from MSSQL is correct (I've checked).
Here's my Export file:
error_reporting(E_ALL);
ini_set('display_errors', 1);
include('DBConn.php');
include 'Helper/LogReport.php';
if(isset($_GET['Id']))
{
$id = $_GET['Id'];
$query = $conn->prepare('SELECT QName, tsql from pmdb.QDefs WHERE Id = ' . $id);
$query->execute();
$qdef = $query->fetch(PDO::FETCH_ASSOC);
}
else
{
$query = $conn->prepare("SELECT QName, tsql from pmdb.QDefs WHERE QName = '" .$TableName. "'");
$query->execute();
$qdef = $query->fetch(PDO::FETCH_ASSOC);
}
// Create and open file for writing
$filepath = 'exports/';
$filename = $qdef['QName'] . '.csv';
try
{
header('Content-Encoding: UTF-8');
header('Content-Type: text/csv; charset:UTF-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
}
catch(Exception $e)
{
echo "Something went wrong<br>";
die( print_r( $e->getMessage()));
}
//define separators
$sep = ","; //separator
$br = "\r\n"; //line break
// Use returned tsql field as query for dataset
$tsql = $qdef['tsql'];
if(isset($DataReturn))
{
if(strpos($DataReturn['Order'],'EDIT'))
{
$DataReturn['Order'] = str_replace('EDIT','Id',$DataReturn['Order']);
}
$tsql = $tsql . $DataReturn['WhereClause'] . $DataReturn['Order'] . $DataReturn['Limit'];
}
$query = $conn->prepare($tsql);
$query->execute();
// Output data to CSV file
$headers = NULL;
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
//Write column headings to file
if (is_null($headers))
{
$headers = array_keys($row);
if ($headers[0] == 'ID')
$headers[0] = 'Id';
foreach($headers as $Header)
{
echo $Header. ",";
}
echo $br;
}
//Write data
$modRow = preg_replace('/ \d{2}:\d{2}:\d{2}\.\d{3}/', '', $row);
$modRow = preg_replace( "/\r|\n/", "", $modRow );
foreach($modRow as $RowPrint)
{
echo '"' .trim(unserialize(serialize($RowPrint))). '"' .$sep;
}
echo $br;
}
I don't see anything that would stop the data stream from completing the export.
EDIT
I have tried the fputcsv() method like this:
error_reporting(E_ALL);
ini_set('display_errors', 1);
include('DBConn.php');
include 'Helper/LogReport.php';
//print_r($_GET);
if(isset($_GET['Id']))
{
$id = $_GET['Id'];
$query = $conn->prepare('SELECT QName, tsql from pmdb.QDefs WHERE Id = ' . $id);
$query->execute();
$qdef = $query->fetch(PDO::FETCH_ASSOC);
}
else
{
$query = $conn->prepare("SELECT QName, tsql from pmdb.QDefs WHERE QName = '" .$TableName. "'");
$query->execute();
$qdef = $query->fetch(PDO::FETCH_ASSOC);
}
// Create and open file for writing
$filepath = 'exports/';
$filename = $qdef['QName'] . '.csv';
try
{
$openFile = fopen($filepath . $filename,'a');
header('Content-Encoding: UTF-8');
header('Content-Type: text/csv; charset:UTF-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
}
catch(Exception $e)
{
echo "Something went wrong<br>";
die( print_r( $e->getMessage()));
}
//define separators
$sep = ","; //separator
$br = "\r\n"; //line break
// Use returned tsql field as query for dataset
$tsql = $qdef['tsql'];
if(isset($DataReturn))
{
if(strpos($DataReturn['Order'],'EDIT'))
{
$DataReturn['Order'] = str_replace('EDIT','Id',$DataReturn['Order']);
}
$tsql = $tsql . $DataReturn['WhereClause'] . $DataReturn['Order'] . $DataReturn['Limit'];
}
$query = $conn->prepare($tsql);
$query->execute();
// Output data to CSV file
$headers = NULL;
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
//Write column headings to file
if (is_null($headers))
{
$headers = array_keys($row);
if ($headers[0] == 'ID')
$headers[0] = 'Id';
fputcsv($openFile, $headers);
}
//Write data
$modRow = preg_replace('/ \d{2}:\d{2}:\d{2}\.\d{3}/', '', $row);
$modRow = preg_replace( "/\r|\n/", "", $modRow );
fputcsv($openFile, $modRow, ',','"');//print_r($modRow);
foreach($modRow as $RowPrint)
{
error_log(date("Y/m/d h:i:sa "). ' RowPrint: ' .$RowPrint. '\n',3,'C:\Temp\LogPHP.txt');
}
echo $br;
}
// Close file
fclose($openFile);
This just creates an empty file.
UPDATE
I ran a couple of reports for one that should have 103k+ rows. They both stopped between 61000 and 62000 rows. I did a character count and they both have around 40 million. I don't see anything about a 40million character limit.
I got it working and figured out how to get the fputcsv to work.
I needed to add an exit() to the end of the export. Now it not only sends all the data fputcsv works as well. I got the answer from another question that I ask about getting fputcsv to work.

fputcsv - columns from table displayed in one column

I have a problem with putting data from mysql database to csv file. The column headers are ok but rest of rows from table are in one column. Please help..
<?php
$con=mysqli_connect("localhost","asasdd","asasdasd","asdasd");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen('php://output', 'w');
$array = array("Id;Imie_i_nazwisko;Nazwa_kursu;Data_kursu");
$array = str_replace('"', '', $array);
fputcsv($output, $array);
$rows = mysqli_query($con, 'SELECT * FROM kursanci');
while ($row = mysqli_fetch_assoc($rows))
{
fputcsv($output, $row);
}
mysqli_close($con);
?>
Resolved should be like this:
<?php
$con=mysqli_connect("localhost","asd","asd","asd");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen('php://output', 'w');
$array = array('Id','Imie_i_nazwisko','Nazwa_kursu','Data_kursu');
fputcsv($output, $array, ';');
$rows = mysqli_query($con, 'SELECT * FROM kursanci');
while ($row = mysqli_fetch_assoc($rows))
{
fputcsv($output, $row, ';');
}
mysqli_close($con);
?>
CSV files expects "," as separator. Only MS-Excel uses ";" as separator by default.
Replace ; for ,, make your array with multiples elements for your header and be happy!
$array = array("Id;Imie_i_nazwisko;Nazwa_kursu;Data_kursu");
$array = array('Id','Imie_i_nazwisko','Nazwa_kursu','Data_kursu');
If you are using MS-Excel and/or need to use ";" as separator, just use this:
$array = array('Id','Imie_i_nazwisko','Nazwa_kursu','Data_kursu');
fputcsv($output, $array, ';');
....
fputcsv($output, $row, ';');
....

Exporting table to CSV via php button

I am really new to php and everything I have learned is from my school textbook and online research. With that said I am trying to complete an assignment and I am stuck on the last part. for the final part the assignment says to "Create a PHP script that will dump the contents of the employee table into CSV text file that has comma separated values for each record. Each new record should begin on a new line". I have tried many online tutorials but none of them teach how to put this event in a button. I am including my code so you can see the mess I have. It's not to bad but I am sure I can do the same task with much less code. Again I am just starting out and this is the best I can do for now. Could anyone give any suggestions on how this could be done. I have my button on line 140. I also used a db_connect() function so i don't have to write it many times. I can peon use this to read the database before I save as a csv.
Any suggestions would be greatly appreciated. Be warned It's a lot of code to follow.
<h2>Employee Search</h2>
<form action="Draft.php" name="dbToCSV" method="GET">
<input type="submit" name="dbToCSV" value="Export Database to CSV" <?php if (isset($_GET['dbToCSV']))
{
//Do this code
}
else
{
echo "Error!";
} ?>><br />
</form>
<form action="Draft.php" method="GET">
By name: <input type="text" name="searchName">
<input type="submit" value="Search Name"><br />
</form>
<form action="Draft.php" method="GET">
By language: <input type="text" name="searchLang">
<input type="submit" value="Search Language"><br />
</form>
It's 2017 and mysqli is more common than mysql now. So here's a mysqli version of Josh Liptzin's answer:
<?php
/* Attempt MySQL server connection. */
$connection = mysqli_connect($database_server, $database_username, $database_password, $database_name);
// Check connection
if($connection === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$query = "SELECT * FROM Employee_data";
$result = mysqli_query($connection, $query);
$number_of_fields = mysqli_num_fields($result);
$headers = array();
for ($i = 0; $i < $number_of_fields; $i++) {
$headers[] = mysqli_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 = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
function mysqli_field_name($result, $field_offset)
{
$properties = mysqli_fetch_field_direct($result, $field_offset);
return is_object($properties) ? $properties->name : null;
}
?>
You are literally trying to put the PHP code inside the HTML button. The button can simply be a link to another page (like dump.php), which contains some PHP like the following:
Link:
Download employee data
dump.php:
<?php
$result = mysql_query('SELECT * FROM `employee_data`');
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 = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
?>
Code source: PHP code to convert a MySQL query to CSV
For your own sake you shouldn't copy and paste the above code into your assignment - there's a world of difference between the code you posted and the code above that the grader will instantly pick up on.
So the class is over and I figure I would show how I resolved my issue. this made the most sense to me and it didn't take many lines of code. I am sure there are possibly even shorter ways to do this but for being very new to php i thing I did an ok job with the code.
I basically made an if statement that checks if there are any records in the database then it takes each record field and writes it to the cdv file while adding a comma. I did this code twice. The top code writes the database field names and the second half writes the values in those fields. Thanks for the advice everyone. I am glad I was able to figure it out in time to submit my assignment.
if (isset($_GET['dbToCSV']))
{
// database connection
db_connect();
$query = mysql_query("SELECT * FROM employee_data") or die(mysql_error());
$number_rows = mysql_num_rows($query);
if ($number_rows >= 1)
{
$filename = "exported_db_" . date("m-d-Y_hia") . ".csv"; // filenme with date appended
$fp = fopen($filename, "w"); // open file
$row = mysql_fetch_assoc($query);
$seperator = "";
$comma = "";
foreach ($row as $name => $value)
{
$seperator .= $comma . $name; // write first value without a comma
$comma = ","; // add comma in front of each following value
}
$seperator .= "\n";
echo "Database has been exported to $filename";
fputs($fp, $seperator);
mysql_data_seek($query, 0); // use previous query leaving out first row
while($row = mysql_fetch_assoc($query))
{
$seperator = "";
$comma = "";
foreach ($row as $name => $value)
{
$seperator .= $comma . $value; // write first value without a comma
$comma = ","; // add comma in front of each following value
}
$seperator .= "\n";
fputs($fp, $seperator);
}
fclose($fp);
}
else
echo "There are no records in the database to export.";
mysql_close();
}
Following is PHP script which I am using.
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$table_name = "employees";
$fp = fopen('php://output', 'w');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="'.$table_name.'.csv"');
header('Pragma: no-cache');
header('Expires: 0');
$result = mysql_query("SELECT * FROM $table_name");
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);
}
if ($fp && $result) {
fputcsv($fp, $headers);
while ($row = mysql_fetch_assoc($result)) {
fputcsv($fp, $row);
}
}
exit;
?>

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