How to export data to an excel file using PHPExcel - php

I have taken the source code from limesurvey and have added the PHPExcel library to my limesurvey code to export data to an excel file after you click a link. Currently the excel file opens with some dummy data in it with no problems. I need to be able to add data dynamically from the web server after a user types in survey information. I have looked into some sites I have found but I havent had much luck. Can anyone help me out?
EDIT
<?php
$dbhost= "mysql"; //your MySQL Server
$dbuser = "survey"; //your MySQL User Name
$dbpass = "password"; //your MySQL Password
$dbname = "database";
//your MySQL Database Name of which database to use this
$tablename = "questions"; //your MySQL Table Name which one you have to create excel file
// your mysql query here , we can edit this for your requirement
$sql = "Select * from $table ";
//create code for connecting to mysql
$Connect = #mysql_connect($dbhost, $dbuser, $dbpass)
or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database
$Db = #mysql_select_db($dbname, $Connect)
or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());
//execute query
$result = #mysql_query($sql,$Connect)
or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
error_reporting(E_ALL);
require_once '../Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
// Initialise the Excel row number
$rowCount = 1;
//start of printing column names as names of MySQL fields
$column = 'A';
for ($i = 1; $i < mysql_num_fields($result); $i++)
{
$objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, mysql_field_name($result,$i));
$column++;
}
//end of adding column names
//start while loop to get data
$rowCount = 2;
while($row = mysql_fetch_row($result))
{
$column = 'A';
for($j=1; $j<mysql_num_fields($result);$j++)
{
if(!isset($row[$j]))
$value = NULL;
elseif ($row[$j] != "")
$value = strip_tags($row[$j]);
else
$value = "";
$objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, $value);
$column++;
}
$rowCount++;
}
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="results.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');

If you've copied this directly, then:
->setCellValue('B2', Ackermann')
should be
->setCellValue('B2', 'Ackermann')
In answer to your question:
Get the data that you want from limesurvey, and use setCellValue() to store those data values in the cells where you want to store it.
The Quadratic.php example file in /Tests might help as a starting point: it takes data from an input form and sets it to cells in an Excel workbook.
EDIT
An extremely simplistic example:
// Create your database query
$query = "SELECT * FROM myDataTable";
// Execute the database query
$result = mysql_query($query) or die(mysql_error());
// Instantiate a new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
// Initialise the Excel row number
$rowCount = 1;
// Iterate through each result from the SQL query in turn
// We fetch each database result row into $row in turn
while($row = mysql_fetch_array($result)){
// Set cell An to the "name" column from the database (assuming you have a column called name)
// where n is the Excel row number (ie cell A1 in the first row)
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['name']);
// Set cell Bn to the "age" column from the database (assuming you have a column called age)
// where n is the Excel row number (ie cell A1 in the first row)
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['age']);
// Increment the Excel row counter
$rowCount++;
}
// Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
// Write the Excel file to filename some_excel_file.xlsx in the current directory
$objWriter->save('some_excel_file.xlsx');
EDIT #2
Using your existing code as the basis
// Instantiate a new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
// Initialise the Excel row number
$rowCount = 1;
//start of printing column names as names of MySQL fields
$column = 'A';
for ($i = 1; $i < mysql_num_fields($result); $i++)
{
$objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, mysql_field_name($result,$i));
$column++;
}
//end of adding column names
//start while loop to get data
$rowCount = 2;
while($row = mysql_fetch_row($result))
{
$column = 'A';
for($j=1; $j<mysql_num_fields($result);$j++)
{
if(!isset($row[$j]))
$value = NULL;
elseif ($row[$j] != "")
$value = strip_tags($row[$j]);
else
$value = "";
$objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, $value);
$column++;
}
$rowCount++;
}
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Limesurvey_Results.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');

Try the below complete example for the same
<?php
$objPHPExcel = new PHPExcel();
$query1 = "SELECT * FROM employee";
$exec1 = mysql_query($query1) or die ("Error in Query1".mysql_error());
$serialnumber=0;
//Set header with temp array
$tmparray =array("Sr.Number","Employee Login","Employee Name");
//take new main array and set header array in it.
$sheet =array($tmparray);
while ($res1 = mysql_fetch_array($exec1))
{
$tmparray =array();
$serialnumber = $serialnumber + 1;
array_push($tmparray,$serialnumber);
$employeelogin = $res1['employeelogin'];
array_push($tmparray,$employeelogin);
$employeename = $res1['employeename'];
array_push($tmparray,$employeename);
array_push($sheet,$tmparray);
}
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="name.xlsx"');
$worksheet = $objPHPExcel->getActiveSheet();
foreach($sheet as $row => $columns) {
foreach($columns as $column => $data) {
$worksheet->setCellValueByColumnAndRow($column, $row + 1, $data);
}
}
//make first row bold
$objPHPExcel->getActiveSheet()->getStyle("A1:I1")->getFont()->setBold(true);
$objPHPExcel->setActiveSheetIndex(0);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
?>

$this->load->library('excel');
$file_name = 'Demo';
$arrHeader = array('Name', 'Mobile');
$arrRows = array(0=>array('Name'=>'Jayant','Mobile'=>54545), 1=>array('Name'=>'Jayant1', 'Mobile'=>44454), 2=>array('Name'=>'Jayant2','Mobile'=>111222), 3=>array('Name'=>'Jayant3', 'Mobile'=>99999));
$this->excel->getActiveSheet()->fromArray($arrHeader,'','A1');
$this->excel->getActiveSheet()->fromArray($arrRows);
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$file_name.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
$objWriter->save('php://output');

Work 100%. maybe not relation to creator answer but i share it for users have a problem with export mysql query to excel with phpexcel.
Good Luck.
require('../phpexcel/PHPExcel.php');
require('../phpexcel/PHPExcel/Writer/Excel5.php');
$filename = 'userReport'; //your file name
$objPHPExcel = new PHPExcel();
/*********************Add column headings START**********************/
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'username')
->setCellValue('B1', 'city_name');
/*********************Add data entries START**********************/
//get_result_array_from_class**You can replace your sql code with this line.
$result = $get_report_clas->get_user_report();
//set variable for count table fields.
$num_row = 1;
foreach ($result as $value) {
$user_name = $value['username'];
$c_code = $value['city_name'];
$num_row++;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$num_row, $user_name )
->setCellValue('B'.$num_row, $c_code );
}
/*********************Autoresize column width depending upon contents START**********************/
foreach(range('A','B') as $columnID) {
$objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
}
$objPHPExcel->getActiveSheet()->getStyle('A1:B1')->getFont()->setBold(true);
//Make heading font bold
/*********************Add color to heading START**********************/
$objPHPExcel->getActiveSheet()
->getStyle('A1:B1')
->getFill()
->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
->getStartColor()
->setARGB('99ff99');
$objPHPExcel->getActiveSheet()->setTitle('userReport'); //give title to sheet
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment;Filename=$filename.xls");
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');

I currently use this function in my project after a series of googling to download excel file from sql statement
// $sql = sql query e.g "select * from mytablename"
// $filename = name of the file to download
function queryToExcel($sql, $fileName = 'name.xlsx') {
// initialise excel column name
// currently limited to queries with less than 27 columns
$columnArray = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
// Execute the database query
$result = mysql_query($sql) or die(mysql_error());
// Instantiate a new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
// Initialise the Excel row number
$rowCount = 1;
// fetch result set column information
$finfo = mysqli_fetch_fields($result);
// initialise columnlenght counter
$columnlenght = 0;
foreach ($finfo as $val) {
// set column header values
$objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$columnlenght++] . $rowCount, $val->name);
}
// make the column headers bold
$objPHPExcel->getActiveSheet()->getStyle($columnArray[0]."1:".$columnArray[$columnlenght]."1")->getFont()->setBold(true);
$rowCount++;
// Iterate through each result from the SQL query in turn
// We fetch each database result row into $row in turn
while ($row = mysqli_fetch_array($result, MYSQL_NUM)) {
for ($i = 0; $i < $columnLenght; $i++) {
$objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$i] . $rowCount, $row[$i]);
}
$rowCount++;
}
// set header information to force download
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
// Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file
// Write the Excel file to filename some_excel_file.xlsx in the current directory
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
// Write the Excel file to filename some_excel_file.xlsx in the current directory
$objWriter->save('php://output');
}

// gl and gl2 excel file Export Program
public function glExcelFileExport()
{
$from_date1 = $this->input->post('from_date1');
$to_date1 = $this->input->post('to_date1');
$account_number = $this->input->post('account_number');
$glnames = $this->input->post('glnames');
$sql = "SELECT * FROM ut_sbi_reco_rungl WHERE value_date between '".$from_date1."' AND '".$to_date1."' ";
$result = $this->db->query($sql)->result_array();
if(count($result)>0)
{
require FCPATH . 'vendor/autoload.php';
$object = new PHPExcel();
$prestasi = $object->setActiveSheetIndex(0);
//manage row hight
$object->getActiveSheet()->getRowDimension(1)->setRowHeight(25);
// Excel Heading Description
if($glnames == 'gl1') {
//style alignment
$styleArray = array(
'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
),
);
$object->getActiveSheet()->getStyle('A1:U1')->getFont()->setBold(true);
$object->getActiveSheet()->getStyle('A1:U1')->applyFromArray($styleArray);
//border
$styleArray1 = array(
'borders' => array(
'allborders' => array(
'style' => PHPExcel_Style_Border::BORDER_THIN
)
)
);
//background
$styleArray12 = array(
'fill' => array(
'type' => PHPExcel_Style_Fill::FILL_SOLID,
'startcolor' => array(
'rgb' => 'FFFF00',
),
),
);
//freeepane
$object->getActiveSheet()->freezePane('A2');
//column width
$object->getActiveSheet()->getColumnDimension('A')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('B')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('C')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('D')->setWidth(20);
$object->getActiveSheet()->getColumnDimension('E')->setWidth(20);
$object->getActiveSheet()->getColumnDimension('F')->setWidth(12);
$object->getActiveSheet()->getColumnDimension('G')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('H')->setWidth(20);
$object->getActiveSheet()->getColumnDimension('I')->setWidth(20);
$object->getActiveSheet()->getColumnDimension('J')->setWidth(20);
$object->getActiveSheet()->getColumnDimension('K')->setWidth(20);
$object->getActiveSheet()->getColumnDimension('L')->setWidth(10);
$object->getActiveSheet()->getColumnDimension('M')->setWidth(12);
$object->getActiveSheet()->getColumnDimension('N')->setWidth(25);
$object->getActiveSheet()->getColumnDimension('O')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('P')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('Q')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('R')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('S')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('T')->setWidth(25);
$object->getActiveSheet()->getColumnDimension('U')->setWidth(15);
$object->getActiveSheet()->getStyle('A1:U1')->applyFromArray($styleArray1);
$object->getActiveSheet()->getStyle('A1:U1')->applyFromArray($styleArray12);
$object->getActiveSheet()->getStyle('I')->getNumberFormat()->setFormatCode("0.00");
$table_columns = array("SRL", "Scheme", "Tran Type", "App Refer", "OTH Refer",
"Account", "Name", "Value Date", "Amount", "Pay Category", "Rev Flg",
"Security", "Cheque Number", "SCH", "Book Date", "Cheque Date",
"Reg Id", "Inputter", "Narration", "FL", "Batch Number");
$column = 0;
foreach($table_columns as $field)
{
$object->getActiveSheet()->setCellValueByColumnAndRow($column, 1, $field);
$column++;
}
}
if($glnames == 'gl2') {
//style alignment
$styleArray = array(
'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
),
);
$object->getActiveSheet()->getStyle('A1:C1')->getFont()->setBold(true);
$object->getActiveSheet()->getStyle('A1:C1')->applyFromArray($styleArray);
//border
$styleArray1 = array(
'borders' => array(
'allborders' => array(
'style' => PHPExcel_Style_Border::BORDER_THIN
)
)
);
//background
$styleArray12 = array(
'fill' => array(
'type' => PHPExcel_Style_Fill::FILL_SOLID,
'startcolor' => array(
'rgb' => 'FFFF00',
),
),
);
//freeepane
$object->getActiveSheet()->freezePane('A2');
//column width
$object->getActiveSheet()->getColumnDimension('A')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('B')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('C')->setWidth(15);
$object->getActiveSheet()->getStyle('A1:C1')->applyFromArray($styleArray1);
$object->getActiveSheet()->getStyle('A1:C1')->applyFromArray($styleArray12);
$object->getActiveSheet()->getStyle('C')->getNumberFormat()->setFormatCode("0.00");
$table_columns1 = array("Account", "Name", "Amount");
$column1 = 0;
foreach($table_columns1 as $field1)
{
$object->getActiveSheet()->setCellValueByColumnAndRow($column1, 1, $field1);
$column1++;
}
}
// List of column names
$style = array(
'alignment' => array(
'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
)
);
$prestasi->getDefaultStyle()->applyFromArray($style);
if($glnames == 'gl1') {
// Gl1 Query
$excel_row = 2;
for ($kk=0;$kk<count($account_number);$kk++)
{
$account_number2 = $account_number[$kk];
$gl1Arr = $this->ut_gl_model->getDisplayGl1Query($account_number2,$from_date1,$to_date1);
foreach($gl1Arr as $row)
{
$object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row, $row['srl']);
$object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row, $row['scheme']);
$object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row, $row['tran_type']);
$object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row, $row['app_refer']);
$object->getActiveSheet()->setCellValueByColumnAndRow(4, $excel_row, $row['oth_refer']);
$object->getActiveSheet()->setCellValueByColumnAndRow(5, $excel_row, $row['account']);
$object->getActiveSheet()->setCellValueByColumnAndRow(6, $excel_row, $row['name']);
$object->getActiveSheet()->setCellValueByColumnAndRow(7, $excel_row, (isset($row['value_date']) && $row['value_date']!='0000-00-00')?date('d/m/Y',strtotime($row['value_date'])):'');
$object->getActiveSheet()->setCellValueByColumnAndRow(8, $excel_row, $row['amt']);
$object->getActiveSheet()->setCellValueByColumnAndRow(9, $excel_row, $row['pay_catego']);
$object->getActiveSheet()->setCellValueByColumnAndRow(10, $excel_row, $row['rev_flg']);
$object->getActiveSheet()->setCellValueByColumnAndRow(11, $excel_row, $row['security']);
$object->getActiveSheet()->setCellValueByColumnAndRow(12, $excel_row, $row['chq_number']);
$object->getActiveSheet()->setCellValueByColumnAndRow(13, $excel_row, 'y');
$object->getActiveSheet()->setCellValueByColumnAndRow(14, $excel_row, (isset($row['book_date']) && $row['book_date']!='0000-00-00')?date('d/m/Y',strtotime($row['book_date'])):'');
$object->getActiveSheet()->setCellValueByColumnAndRow(15, $excel_row, (isset($row['chq_date']) && $row['chq_date']!='0000-00-00')?date('d/m/Y',strtotime($row['chq_date'])):'');
$object->getActiveSheet()->setCellValueByColumnAndRow(16, $excel_row, $row['reg_id']);
$object->getActiveSheet()->setCellValueByColumnAndRow(17, $excel_row, $row['inputter']);
$object->getActiveSheet()->setCellValueByColumnAndRow(18, $excel_row, $row['narration']);
$object->getActiveSheet()->setCellValueByColumnAndRow(19, $excel_row, '');
$object->getActiveSheet()->setCellValueByColumnAndRow(20, $excel_row, '');
$excel_row++;
}
}
// Excel Download Logic
$downloadFile = 'gl1_'.date('Ymd').'.xlsx';
$prestasi->setTitle("Gl1 Dump");
$object_writer = PHPExcel_IOFactory::createWriter($object, 'Excel2007');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$downloadFile.'" ');
$object_writer->save('php://output');
}
$excel_row1 = 2;
if($glnames == 'gl2') {
// Gl2 Query
for ($jj=0;$jj<count($account_number);$jj++)
{
$account_number3 = $account_number[$jj];
$gl2Arr = $this->ut_gl_model->getDisplayGl2Query($account_number3,$from_date1,$to_date1);
foreach($gl2Arr as $row1)
{
$object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row1, $row1['account']);
$object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row1, $row1['name']);
$object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row1, $row1['amount']);
// $object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row1, $row1['value_date']);
$excel_row1++;
}
}
// Excel Download Logic
$prestasi->setTitle("Gl2 Dump");
$downloadFile2 = 'gl2_'.date('Ymd').'.xlsx';
$object_writer = PHPExcel_IOFactory::createWriter($object, 'Excel2007');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$downloadFile2.'" ');
$object_writer->save('php://output');
}
}
else
{
$this->session->set_flashdata('error', 'Data not found.');
redirect(site_url('sbi-reco/run-gl'));
}
}

Related

Custom Headers in PHP SQL Query

I have an html form that calls a php document on submit that downloads the values of a table as a csv file. My goal is to utilize the "as" within the select statement to achieve custom column headers within that document. For example, I would like to select tableNAME.address and print to the csv as "Site Location".
Here is a sample of the php along with a postgres query:
<?php
// show error messages
ini_set('error_reporting', E_ALL);
ini_set("display_errors", 1);
if( !empty($_SERVER['REQUEST_METHOD']) && (strcasecmp($_SERVER['REQUEST_METHOD'], 'post')===0) ) {
// Create connection
$conn = pg_connect("host=MYHOST port=ACCESS dbname=DBNAME user=USERNAME password=PWORD");
// Check connection
if (!$conn) {
echo "Did not connect.\n";
exit;
}
$result = pg_query($conn,
"
SELECT
tableNAME.address AS Address,
tableNAME.city AS City,
tableNAME.state_1 AS State,
-- adds 0's if zip code is not long enough
case length(tableNAME.zip)
WHEN 5 THEN tableNAME.zip
WHEN 4 THEN '0' || tableNAME.zip
WHEN 3 THEN '00' || tableNAME.zip
END AS Zip
FROM
db.tableNAME
WHERE
tableNAME.in_process = 'true' and
tableNAME.shippiing = 'false' and
tableNAME.soft_delete_id = '0' and
tableNAME.status_1 <> 'Closed' and
tableNAME.return_shipment = 'true'
ORDER BY
tableNAME.site_id asc;");
if (!$result) {
echo "Query failed.\n";
exit;
}
$num_fields = pg_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = pg_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result)
{
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="ups_returns.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = pg_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
die;
}
exit('It works');
}
?>
I have tried different variations on using apostrophe's within the select as statement. For example...
tableNAME.address as '""Site Location""'
tableNAME.address as 'Site Location'
tableNAME.address as '"Site Location"'
None of these have worked... I believe the line of my code that may need to be altered is:
$headers = array();
However, I have no idea what I can do to make it work.
Thanks
I have found a resolution... Instead of using data from the query to determine headers I set them manually.
$headers = array('Site Location','City','State','Zip','Package Type','Weight','ShippingCode','TicketNumber','ReturnService','Return','BillTo','Attention','SiteID','PrintLabel');
//for ($i = 0; $i < $num_fields; $i++)
//{
// $headers[] = pg_field_name($result , $i);
//}

mysql_fetch_array only returns last value of query [duplicate]

This question already has answers here:
How to store values from foreach loop into an array?
(9 answers)
Closed 1 year ago.
Basically I want to make a download button for my project that will produce different csv files (one csv file per table) in memory and zip before download. It works fine but the problem is that I am only getting one row (the last result) on each mysql_fetch_array where it is supposed to return rows depending on how many are stored in the database. This code is depreciated, sorry for that.
Here is my code:
<?php
require("../includes/connection.php");
require("../includes/myLib.php");
//get the ID that is passed
$ID = $_REQUEST['q'];
$ID = xdec($ID);
//All queries to fetch data
$query = mysql_query("SELECT * FROM `ge2`.`projects` WHERE `projects`.`proj_id`='$ID'");
$query2 = mysql_query("SELECT * FROM `ge2`.`attributes` WHERE `attributes`.`proj_id`='$ID'");
$query3 = mysql_query("SELECT * FROM `ge2`.`category` WHERE `category`.`proj_id`='$ID'");
$query4 = mysql_query("SELECT * FROM `ge2`.`multipletarget` WHERE `multipletarget`.`proj_id`='$ID'");
$query5 = mysql_query("SELECT * FROM `ge2`.`data_cut` WHERE `data_cut`.`proj_id`='$ID'");
$query6 = mysql_query("SELECT * FROM `ge2`.`raw` WHERE `raw`.`proj_id`='$ID'");
//getting all array
while ($row = mysql_fetch_array($query)) {
$proj_alias = $row['proj_alias'];
$proj_id = $row['proj_id'];
$date_added = $row['date_added'];
}
while ($row1 = mysql_fetch_array($query2)) {
$attrib_param_id = $row1['param_id'];
$attrib_proj_id = $row1['proj_id'];
$attrib_cat_id = $row1['cat_id'];
$attrib_val_id = $row1['val_id'];
$attrib_name = $row1['name'];
$attrib_isCust = $row1['isCust'];
}
while ($row2 = mysql_fetch_array($query3)) {
$category_cat_id = $row2['cat_id'];
$category_name = $row2['name'];
$category_proj_id = $row2['proj_id'];
$category_desc = $row2['desc'];
}
while ($row3 = mysql_fetch_array($query4)) {
$multipletarget_id = $row3['id'];
$multipletarget_proj_id = $row3['proj_id'];
$multipletarget_mtarget1 = $row3['mtarget1'];
$multipletarget_mtarget2 = $row3['mtarget2'];
}
while ($row4 = mysql_fetch_array($query5)) {
$data_cut_id = $row4['id'];
$data_cut_proj_id = $row4['proj_id'];
$data_cut_name = $row4['name'];
$data_cut_param = $row4['param'];
$data_cut_lvl = $row4['lvl'];
$data_cut_val = $row4['val'];
}
while ($row5 = mysql_fetch_array($query6)) {
$raw_id = $row5['raw_id'];
$raw_proj_id = $row5['proj_id'];
$raw_p_id = $row5['p_id'];
$raw_url = $row5['url'];
$raw_ip = $row5['ip'];
$raw_pos = $row5['pos'];
$raw_datetaken = $row5['datetaken'];
$raw_used = $row5['used'];
$raw_fdc_id = $row5['fdc_id'];
$raw_dq = $row5['dq'];
}
// some data to be used in the csv files
$records = array(
$proj_alias, $proj_id, $date_added
);
$records2 = array(
$attrib_param_id, $attrib_proj_id, $attrib_cat_id, $attrib_val_id, $attrib_name, $attrib_isCust
);
$records3 = array(
$category_cat_id, $category_name, $category_proj_id, $category_desc
);
$records4 = array(
$multipletarget_id, $multipletarget_proj_id, $multipletarget_mtarget1, $multipletarget_mtarget2
);
$records5 = array(
$data_cut_id, $data_cut_proj_id, $data_cut_name, $data_cut_param,$data_cut_lvl,$data_cut_val
);
$records6 = array(
$raw_id, $raw_proj_id, $raw_p_id, $raw_url,$raw_ip,$raw_pos,$raw_datetaken,$raw_used,$raw_fdc_id,$raw_dq
);
//making an array to be used in loop
$set = array($records,$records2,$records3,$records4,$records5,$records6);
//names to be named for each csv file
$names = array('projects', 'attributes', 'category', 'multipletarget', 'data_cut', 'raw');
// create zip file
$zipname = $proj_alias;
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
// loop to create csv files
$n = 0;
foreach ($set as $setk => $sets) {
$n += 1;
$fd = fopen('php://temp/maxmemory:1048576', 'w');
if (false === $fd) {
die('Failed to create temporary file');
}
fputcsv($fd, $sets);
// return to the start of the stream
rewind($fd);
// add the in-memory file to the archive, giving a name
$zip->addFromString('BrainLink-' . $proj_alias . "-" . $names[$setk] . '.csv', stream_get_contents($fd));
//close the file
fclose($fd);
}
// close the archive
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname.'.zip');
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
// remove the zip archive
// you could also use the temp file method above for this.
unlink($zipname);
?>
Thanks in advance.
Well, it seems that you're independently iterating over all query results and overwriting the variables over and over again. So in the end, you have only last table results to work with.
You might try using JOIN OR UNION SELECT in MySQL to get all the items in one big query result row:
$query = mysql_query('SELECT proj.*, attrs.*
FROM `projects` AS proj
JOIN `attributes` AS attrs ON (attrs.project_id=proj.project_id)
<..more tables to join in the same manner..>
WHERE proj.`proj_id`= ' . $projectId);
And then, you'll just have to iterate only over a single query resource.
while ($row = mysql_fetch_array($query)) {
//your code here
}
Note, that if tables being JOIN'ed have the same column names, they will "overwrite" each other and you'll have to rename them yourself "on the fly".
Like so:
SELECT proj.field, proj.another_field, proj.conflicting_field_name AS unique_field_name
I did not read all of your code, but in each while loop, you only save last record. It should be something like this.
while($row = mysql_fetch_array($query)){
$proj_alias[] = $row['proj_alias'];
$proj_id[] = $row['proj_id'];
$date_added[] = $row['date_added'];
}
and the others like above.

Unable to change date format in Excel using PHP

I am writing lots(around 900 rows) of data into a .xls file using class.writeexcel_worksheet.inc.php PHP class. All data written into excel is treated as simple text, even date and time stamps.
Now the problem is while filtering for dates in excel, there is no filter on for months or year. Since all cell values are simple text. Is there any way to format my cell to date data type while creating excel through PHP code?
CODE:
<?php
require_once "class.writeexcel_workbookbig.inc.php";
require_once "class.writeexcel_worksheet.inc.php";
require_once "db_params.php";
if(isset($_POST['submit']))
{
$heure = date("H_i");
$fname = tempnam("/tmp", $date."_".$heure.".xls");
$workbook = &new writeexcel_workbookbig($fname);
$worksheet = &$workbook->addworksheet();
$mainheading =& $workbook->addformat();
$mainheading->set_color('white');
$mainheading->set_pattern(0x1);
$mainheading->set_align('center');
$mainheading->set_border_color('black');
$mainheading->set_border(1);
$mainheading->set_merge();
$worksheet->write("A1", "Observation", $mainheading, $border2);
$worksheet->set_column(0, 50, 18);
$worksheet->freeze_panes(2, 0); # 1 row
$worksheet->merge_cells("A1:L1");
$heading =& $workbook->addformat();
$heading->set_color('white');
$heading->set_align('center');
$heading->set_align('vcenter');
$worksheet->set_column(0, 50, 18);
//$worksheet->set_outline();
$worksheet->set_margins(2);
# Create a border format
$border1 =& $workbook->addformat();
$border1->set_color('black');
$border1->set_pattern(0x1);
$border1->set_fg_color('white');
$border1->set_border_color('black');
$border1->set_border(1);
$border1->set_text_wrap();
$col=0;
$query = "SELECT * from Incidents";
$res=sqlsrv_query($conn,$query,array(), array('Scrollable'=>SQLSRV_CURSOR_STATIC));
$Entete1 = array("Incident ID - Hyperlink to AR" , "Reported Date", "Service", "Priority", "Operational Categorization Tier 1", "Summary", "Assignment Date", "Status", "Last Assigned Group", "Resolution Status", "Time bef. first assignment", "Number of assignments");
foreach($Entete1 as $value) {
$worksheet->write(1, $col, $value,$heading);
$col++;
}
$col=0;
$Entete11 = array("IncidentID", "ReportDate", "Service", "Priority", "OperationalCategoryT1", "Summary", "AssignmentDate", "Status", "LastAssignedGroup", "ResolutionStatus", "AcknowledgmentTime", "NoOFAssignment", "Team", "Remarks", "RemarkCategory" , "PloneforgeNo" ,"ProdCategorisationT1", "ProdCategorisationT2", "ProdCategorisationT3", "Urgency", "Impact", "Resolved_date", "Category_tier1", "ResolutionDetails", "Name", "LastResolvedDate", "Resolution", "OLAStatus", "OLAUpTime", "ReopenedDate", "StatusReason", "BucketDate", "OLAProgress", "DueDateTime", "GoalTime");
foreach($Entete11 as $value)
{
$x=2;
$y=2;
for( $position = SQLSRV_SCROLL_FIRST ; ($row=sqlsrv_fetch_array($res, SQLSRV_FETCH_BOTH, $position)) ; $position = SQLSRV_SCROLL_NEXT )
{
$chaine = strip_tags($row[$value]);
$worksheet->write($x, $col, $chaine, $border1);
$x++;
}
$col++;
}
$workbook->close();
header("Content-Type: application/x-msexcel; name=".$date."_".$heure.".xls");
header("Content-Disposition: inline; filename=".$date."_".$heure.".xls");
$fh=fopen($fname, "rb");
fpassthru($fh);
unlink($fname);
}
?>

Issue while inserting multiple images using PHPExcel

I want to generate excel report from php,in which there are two images for each row. But the generated excel sheet show images only for the first row.
following is my used code
$pixels = 120;
$points = PHPExcel_Shared_Drawing::pixelsToPoints($pixels);
$wpixels = 95;
$wpoints = PHPExcel_Shared_Drawing::pixelsToPoints($wpixels);
while ($data = mysql_fetch_array($rsExport)) {
#extract($data);
$image_path = "../../../upload/jrf/".$img_upload;
$sign_path = "../../../upload/jrf/".$sign_upload;
$activeSheet->setCellValue("A".$rowNum, $i);
$activeSheet->setCellValue("B".$rowNum, $jrf_roll_no);
$activeSheet->setCellValue("C".$rowNum, $name);
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setPath($image_path);
$objDrawing->setCoordinates('D'.$rowNum);
$objDrawing->setResizeProportional(false);
$objDrawing->setWidth($wpoints);
$objDrawing->setWorksheet($activeSheet);
$activeSheet->getRowDimension($rowNum)->setRowHeight($points);
$activeSheet->getColumnDimension('D'.$rowNum)->setAutoSize(true);
$objDrawing1 = new PHPExcel_Worksheet_Drawing();
$objDrawing1->setPath($sign_path);
$objDrawing1->setCoordinates('E'.$rowNum);
$objDrawing1->setResizeProportional(false);
$objDrawing1->setWidthAndHeight($wpoints,$points);
$objDrawing1->setWorksheet($activeSheet);
$activeSheet->getColumnDimension('E'.$rowNum)->setAutoSize(true);
$rowNum++;
$i++;
}

PHP and excel export

I have problem of decimal places in excel 2013. The amount less than thousand it does not show the decimal otherwise show decimal in Excel cell. Amount with thousand show (1233.00) and if amount less than thousand then show (763).
$datatable = "<table><tr>";
while($nt=mysql_fetch_array($finalquery)) {
$amount= number_format($nt[3],2);
$datatable .= "<td>$amount</td>";
}
$datatable = "</tr></table>";
$dtimestamp= time( );
$ddatetime = date("G-i-s",$dtimestamp);
$filename = "External_data_" . date('dmY') .":". $ddatetime .".xls";
header('Content-type: application/ms-excel');
header("Content-Disposition: attachment; filename=\"" . $filename . "\"");
echo $datatable;
<?php //in moodle
mysql_connect($CFG->dbhost,$CFG->dbuser,$CFG->dbpass);
mysql_select_db($CFG->dbname);
$sql ="SELECT *
FROM dddd c WHERE a.deleted = 0 AND mi.is_deleted='0' AND a.id!='2' and a.regtype!='trial' AND ra.roleid=5 GROUP BY userid";
//$filename = $fname.".csv";
mysql_query("SET NAMES 'utf8'");
$rsSearchResults = mysql_query($sql) or die(mysql_error());
$xlsarr = array();
$xlshead = array();
$xls_lastcolumn='O';
$xl_aplha=createColumnsArray($xls_lastcolumn);
$nums=0;
for($i=0; $i<mysql_num_fields($rsSearchResults);$i++){
$column_name=mysql_fetch_field($rsSearchResults, $i);
$xlshead[$xl_aplha[$nums]]=$column_name->name;
$nums=$nums+1;
}
// $my_xlshead_add=array('15'=>'Registration Code');
// $_xlshead=array_merge($xlshead,$my_xlshead_add);
$xlsarr[] = $xlshead;
//$csvid=0;
while ($l = mysql_fetch_assoc($rsSearchResults)) {
$numk=0;
$l['Password']='';
if($l['Activation Date']=='1970-01-01')
{
$actdate='';
}
else
{
$actdate=date("Y/n/j",strtotime($l['Activation Date']));
}
$l['Activation Date'] = $actdate;
if($l['Expiration Date']=='1970-01-01')
{
$expdate='';
}
else
{
$expdate=date("Y/n/j",strtotime($l['Expiration Date']));
}
$l['Expiration Date'] = $expdate;
$reg_code=get_regcode($l['userid']);
// $my_array_add=array('15'=>$reg_code,'Registration Code'=>$reg_code);
// $_array_merge=array_merge($l,$my_array_add);
// unset($l['userid']);
// Dependent on select query
$xlsdata[$xl_aplha[$numk]]=$l['Coloumn4'];
$xlsdata[$xl_aplha[$numk=$numk+1]]=$l['Coloumn45'];
$xlsdata[$xl_aplha[$numk=$numk+1]]=$l['Coloumn4Name'];
$xlsdata[$xl_aplha[$numk=$numk+1]]=$l['Coloumn443'];
$xlsdata[$xl_aplha[$numk=$numk+1]]=$l['Coloumn4'];
$xlsdata[$xl_aplha[$numk=$numk+1]]=$l['Coloumn4Name'];
$xlsdata[$xl_aplha[$numk=$numk+1]]=$l['Coloumn5Address'];
$xlsdata[$xl_aplha[$numk=$numk+1]]=$l['Coloumn6Number'];
$xlsdata[$xl_aplha[$numk=$numk+1]]=$l['Coloumn7'];
$xlsdata[$xl_aplha[$numk=$numk+1]]=$l['Coloumn8'];
$xlsdata[$xl_aplha[$numk=$numk+1]]=$l['Coloumn9'];
$xlsdata[$xl_aplha[$numk=$numk+1]]=$l['Coloumn10Code'];
$xlsarr[]=$xlsdata;
// $csvid++;
}
// pr($xlsarr);
$fname = "Elsevier_Users";
//printExcel2($csvarr,"xls",$fname,false);
$myfilename=$fname.'.xls';
myprintExcel($xlsarr,$xls_lastcolumn,$myfilename);
?>///for excel import and export
function myprintExcel($xlsarr,$LastColumn,$filesname){
// global $CFG;
// require_once($CFG->libdir.'/phpmailer/class.phpmailer.php');
global $filePath;
ob_start();
include ($filePath.'/PHPExcel/Classes/PHPExcel.php');
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("XLSX")
->setLastModifiedBy("XLSX")
->setTitle("XLSX")
->setSubject("XLSX")
->setDescription("XLSX")
->setKeywords("XLSX")
->setCategory("ElsevierUsers");
// Add some data
$val=0;
//echo '<pre>';
//print_r($xlsarr);
//die();
foreach ($xlsarr as $arykey=>$aryLine)
{
$rowInd = $arykey+1;
$lastcol=createColumnsArray($LastColumn);
foreach ($lastcol as $key=>$char) {
// echo $aryLine[$i_count].$char.$arykey . "\n";
$objPHPExcel->setActiveSheetIndex(0)->setCellValue($char.$rowInd, $aryLine[$char]);
}
$val++;
}
$objPHPExcel->getActiveSheet()->setTitle('ElsevierUsers');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Query Database
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filesname.'"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
}

Categories