Say I have stored a query in a variable called $query. I want to create small hyper link called "export as CSV" on the results page. How do i do this?
$query = "SELECT * FROM table_name";
$export = mysql_query ($query ) or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $export , $i ) . "\t";
}
while( $row = mysql_fetch_row( $export ) )
{
$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(0) Records Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
ehm ?
Export as CSV
and if you are looking for script wich can do this:
$myArray = array ();
$fp = fopen('export.csv', 'w');
foreach ($myArray as $line) {
fputcsv($fp, split(',', $line));
}
fclose($fp);
CSV = Comma Separated Values = Separate your Values with Commas
you have to echo / print your result line by line, separated with comma (,).
I assume your $query is the result set of your query, which is an associative array:
while($query = mysql_fetch_assoc($rs)) {
// loop till the end of records
echo $query["field1"] . "," . $query["field2"] . "," . $query["field3"] . "\r\n";
}
where $rs is the resource handle.
To let the browser pops up a download box, you must set the header at the beginning of the file (assume your file name is export.csv):
header("Expires: 0");
header("Cache-control: private");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Description: File Transfer");
header("Content-Type: application/vnd.ms-excel");
header("Content-disposition: attachment; filename=export.csv");
That's it!
p.s. This method won't leave a physical file in the server. If you intended to generate a file in the server, use traditional fopen and fwrite functions.
Related
I have 2 tables in the database deliverydata and deliverydata1. I want to append them and export the result as a excel sheet. Here is my sql to excel export script for deliverydata table. What code should I add to append them and export the output as excel sheet. Both the tables have the same number of columns with the same name.
Here is my code :
<?php
include 'db.php';
$SQL = "SELECT WayFrom,WayTo,ConsignorName,ConsigneeName,PODStatus from deliverydata";
$header = '';
$result ='';
$exportData = mysql_query ($SQL ) or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $exportData );
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $exportData , $i ) . "\t";
}
while( $row = mysql_fetch_row( $exportData ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$result .= trim( $line ) . "\n";
}
$result = str_replace( "\r" , "" , $result );
if ( $result == "" )
{
$result = "\nNo Record(s) Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=export.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$result";
?>
Thanks #iainn for your suggestion. It worked :)
#rafael Yes I'm using phpexcel library
#parfait the current code was working properly but I wanted to append two tables
I am using given below code to export database data in to excel sheet,But data in export properly & HTML code also display
$Year="15";
$sql = "select * from table WHERE CurYear=$Year ORDER BY id";
$header = '';
$data ='';
$export = mysql_query($sql) or die(mysql_error($con));
while ($fieldinfo=mysql_fetch_field($export)){
$header .= $fieldinfo->name."\t";
}
while( $row = mysql_fetch_row( $export ) ){
$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 = "\nNo Record(s) Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=export.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
Been trying to figure this out since a hell of a lot of hours, but without result. A user can select some filters in a form, which result in a unique table, printed to the screen.
Then I want a button to export this specific table to a csv file, stored on the users computer.
if(isset($_POST["askReport"])){
//all the variables
//...
$myQuery = ""SELECT *, TIME_TO_SEC(stopwerkdagU) - TIME_TO_SEC(startwerkdagU) - pauzetijdU AS totaalurenU, TIME_TO_SEC(stopwerkdagU) - TIME_TO_SEC(startwerkdag) - pauzetijd AS totaaluren FROM `newRegister` $u $aP $pD $uF $sD"";
$result = $mysqli->query($myQuery);
if($result->num_rows >0){
print '<table><tr><th>.....'; //and all the headers
print '<td>'.$row["user"].'</td>';
..... //and all the other columns and end of row
}
So far, so good, I get a nice table with the results that I want. But then comes the tricky part - how do I get the button to download this table? Here's what I tried: (this code is stil in the isset($_POST["askReport"]) if statement)
// DOWNLOAD TABEL
print '<form method="POST"><button name=download>download</button></form>';
if(isset($_POST["download"])){
$select = "SELECT *, TIME_TO_SEC(stopwerkdagU) - TIME_TO_SEC(startwerkdagU) - pauzetijdU AS totaalurenU, TIME_TO_SEC(stopwerkdagU) - TIME_TO_SEC(startwerkdag) - pauzetijd AS totaaluren FROM `newRegister` $u $aP $pD $uF $sD";
$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $export , $i ) . "\t";
}
while( $row = mysql_fetch_row( $export ) )
{
$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(0) Records Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=download .xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
};
}
This doesn't give any errors. It just reloads the page. So I can't figure out why it isn't working. I thank you for your help.
PARTIAL SOLUTION
The following code (your code, just with the MySQL commented out for testing purposes) works fine. I'm running Apache/2.4.9 (Unix) PHP/5.5.14
The thing that made the downloading work was when I put the <?php and ?> tags in. Try this code and let me know if it works.
<?php
// DOWNLOAD TABEL
print '<form method="POST"><button name=download>download</button></form>';
if(isset($_POST["download"])){
$select = "SELECT *, TIME_TO_SEC(stopwerkdagU) - TIME_TO_SEC(startwerkdagU) - pauzetijdU AS totaalurenU, TIME_TO_SEC(stopwerkdagU) - TIME_TO_SEC(startwerkdag) - pauzetijd AS totaaluren FROM `newRegister` $u $aP $pD $uF $sD";
/* $export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $export , $i ) . "\t";
}
while( $row = mysql_fetch_row( $export ) )
{
$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(0) Records Found!\n";
}
$header="abc,123";
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=download .xls");
header("Pragma: no-cache");
header("Expires: 0");
echo "$header\n$data";
};
?>
How do i make the columns wider and the headers different other than the column name of the table in mysql? and how do i make it have a larger font? I am new to exporting excel files i have no idea how to do it, i've tried researching about it but i didn't understand it either. thank you in advance for your help.
Here is my export.php
<?php
require 'config.php';
$SQL = "SELECT prod_brand, prod_name, prod_category, prod_price, prod_desc, prod_quantity from inventory";
$header = '';
$result ='';
$exportData = mysql_query ($SQL ) or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $exportData );
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $exportData , $i ) . "\t";
}
while( $row = mysql_fetch_row( $exportData ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$result .= trim( $line ) . "\n";
}
$result = str_replace( "\r" , "" , $result );
if ( $result == "" )
{
$result = "\nNo Record(s) Found!\n";
}
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename=InventoryExport'.date('m-d-Y H:i:s').'.xls');
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$result";
?>
See the PHP code sample from this link, where the headers names are custom and the rows are extracted from a database:
http://www.easyxls.com/manual/basics/export-list-to-excel.html
To increase the font size of the header use this code:
// Create an instance of the object used to format the cells
$xlsAutoFormat = new COM("EasyXLS.ExcelAutoFormat");
//Set the style of the header
$xlsHeaderStyle = new COM("EasyXLS.ExcelStyle");
$xlsHeaderStyle->setFontSize(18);
$xlsAutoFormat->setHeaderRowStyle($xlsHeaderStyle);
I am currently able to export my MySQL query to a tab delimited text file, however it is saving with a UTF8 encoding. A requirement of this project is that it saves as a Unicode-16LE text file.
My current function looks something like this:
$select = "SELECT -removed-";
$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $export );
for ($i = 0; $i < $fields; $i++) {
$header .= mysql_field_name( $export , $i ) . "\t";
}
while ($row = mysql_fetch_row($export)) {
$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 );
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=my_file.txt");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
Any advice would be appreciated!
Thanks in advance.
HTTP headers are fairly irrelevant when you are creating a file from database info. Since your app is currently using UTF-8, you have two choices:
Fetch the information directly in UTF-16, i.e., run SET NAMES somethingelse instead of SET NAMES utf8, where somethingelse is your target encoding. You can fetch available encodings with SHOW CHARSET.
Fetch the information in UTF-8 and convert it to Unicode-16LE before saving it to file. You can use iconv() or mb_convert_encoding().