Convert a mysql for loop to mysqli for loop - php

I found a piece of code on the internet that does exactly what I was looking for. The code is about downloading the mysql data into excel sheet format using PHP mysql.
The problem is that I need to convert mysql to mysqli functions and it doesn't seems to work. The for loop needs to be completely changed. Any suggestions?
$conn = mysqli_connect("localhost","root","","dvarsam2"); //server,username,password,db
mysqli_query($conn,'SET NAMES utf8');
$setCounter = 0;
$setExcelName = "download_excal_file";
$setSql = "SELECT * FROM wp_applications";
$setRec = mysqli_query($conn,$setSql);
$setCounter = mysql_num_fields($setRec);
for ($i = 0; $i < $setCounter; $i++) {
$setMainHeader .= mysql_field_name($setRec, $i)."\t";
}
while($rec = mysql_fetch_row($setRec)) {
$rowLine = '';
foreach($rec as $value) {
if(!isset($value) || $value == "") {
$value = "\t";
} else {
//It escape all the special charactor, quotes from the data.
$value = strip_tags(str_replace('"', '""', $value));
$value = '"' . $value . '"' . "\t";
}
$rowLine .= $value;
}
$setData .= trim($rowLine)."\n";
}
$setData = str_replace("\r", "", $setData);
if ($setData == "") {
$setData = "\nno matching records found\n";
}
$setCounter = mysql_num_fields($setRec);
//This Header is used to make data download instead of display the data
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$setExcelName."_Reoprt.xls");
header("Pragma: no-cache");
header("Expires: 0");
//It will print all the Table row as Excel file row with selected column name as header.
echo ucwords($setMainHeader)."\n".$setData."\n";

For MySQLi:
<?php
$conn = mysqli_connect("localhost","root","","dvarsam2"); //server,username,password,db
mysqli_query($conn,'SET NAMES utf8');
$setExcelName = "download_excal_file";
//This Header is used to make data download instead of display the data
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$setExcelName."_Reoprt.xls");
header("Pragma: no-cache");
header("Expires: 0");
$result = mysqli_query( $conn, "SELECT * FROM wp_applications" );
$i = 0;
while( $row = $result->fetch_assoc() )
{
if( $i == 0 )
{
// Print field names
foreach( $row as $key => $value )
{
echo $key."\t";
}
echo "\n";
}
// Print data
foreach( $row as $key => $value )
{
$value = strip_tags(str_replace('"', '""', trim($value)));
echo '"' . str_replace("\r", "", $value ) . '"' . "\t";
}
echo "\n";
$i++;
}
if( $result->num_rows == 0 ) echo "no matching records found\n";

You can also just fix your SELECT statement to format output in Excel format:
SELECT * FROM mytable
INTO OUTFILE '/mytable.csv'
FIELDS ESCAPED BY '""'
TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n';
See here for more. The code you supplied is from the accepted answer, but I prefer this solution.

Related

Append two sql tables and export them as Excel document php

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

Export sql server Query Result in Excel file

I have code to export mysql query result data into Excel. But Now I use SQL Server.I haven't idea to fetch number of fields name. I find many blogs but they all are display php function of mysql database. I need php function which usefull to get field name and number from SQL Query Result
$header = '';
$result = '';
$exportData = sqlsrv_query($gaSql['link'], $sQuery) or die("$sQuery: " . sqlsrv_errors());
$fields = mysql_num_fields($exportData);
for ($i = 0; $i < $fields; $i++) {
if (in_array(mysql_field_name($exportData, $i), $_POST['optFieldName'])) {
$header .= mysql_field_name($exportData, $i) . "\t";
}
// $header .= mysql_field_name($exportData, $i) . "\t";
}
//
$row = array();
for ($i = 0; $i < mysql_num_rows($exportData); $i++) {
$result_excel = mysql_fetch_array($exportData);
array_push($row, $result_excel);
}
foreach ($row as $rowvalue) {
$line = '';
for ($j = 0; $j < count($_POST['optFieldName']); $j++) {
$value = $rowvalue[$_POST['optFieldName'][$j]];
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";

Styling export XLS using PHP

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

Export MySQL to Unicode txt File

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().

export query result as CSV through PHP

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.

Categories