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);
//}
Related
I am using xlsxwriter but nothing work for me, I tried a dozen of things to transfer mysql database row data to excel row data but nothing worked :(
<?php
include_once("xlsxwriter.class.php");
include("connection.php");
ini_set('display_errors', 0);
ini_set('log_errors', 1);
error_reporting(E_ALL & ~E_NOTICE);
$filename = "PM.xlsx";
header('Content-disposition: attachment; filename="'.XLSXWriter::sanitize_filename($filename).'"');
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
$rows = array();
$sql = "SELECT DATE_FORMAT(jobcard.Open_date_time,' %d-%b-%y') AS datee,vehicles_data.Frame_no, jobcard.Jobc_id,jobcard.serv_nature,jobcard.Customer_name,jobc_invoice.Lnet, jobc_invoice.Pnet, jobc_invoice.Snet, jobcard.Mileage,customer_data.cust_type,vehicles_data.model_year,jobcard.Veh_reg_no,jobcard.comp_appointed, customer_data.mobile,IF(variant_codes.Make IS NULL,'Others',variant_codes.Make) as make FROM `jobcard` LEFT OUTER JOIN jobc_invoice ON jobcard.Jobc_id=jobc_invoice.Jobc_id LEFT OUTER JOIN vehicles_data ON jobcard.Vehicle_id=vehicles_data.Vehicle_id LEFT OUTER JOIN variant_codes ON vehicles_data.Model=variant_codes.Model LEFT OUTER JOIN customer_data ON jobcard.Customer_id=customer_data.Customer_id ORDER BY `make` ASC";
$result=mysqli_query($conn,$sql) or die(mysqli_error($sql));
while($rowz = mysqli_fetch_row($result))
{
$rows[] = $rowz;
}
$writer = new XLSXWriter();
$writer->setAuthor('Some Author');
foreach($rows as $row)
$writer->writeSheetRow('Sheet1', $row);
$writer->writeToStdOut();
exit(0);
Even tried this, playing with arrays but nothing fruitful yet.
$row_excel=array();
$row_numb=0;
$writer = new XLSXWriter();
$writer->setAuthor('Some Author');
$result=mysqli_query($conn,$sql) or die(mysqli_error($sql));
while($row = mysqli_fetch_row($result))
{
$row_excel[$row_numb]=$row;
$writer->writeSheetRow('Sheet1', $row_excel[$row_numb]);
$row_numb++;
}
$writer->writeToStdOut();
exit(0);
try this:
while ($row = mysqli_fetch_row($result)) {
$data = array();
for ($i = 0; $i < mysqli_num_fields($result); $i++) {
$data[$i] = $row[$i];
}
$writer->writeSheetRow('Sheet1', $data);
}
$writer->writeToStdOut();
exit(0);
$data = array();
$result=mysqli_query($conn,$sql) or die(mysqli_error($sql));
while ($row = mysqli_fetch_row($result)) {
echo "<br/>";
for ($i = 0; $i < mysqli_num_fields($result); $i++) {
$data[$i] = $row[$i];
echo $row[$i];
}
}
I tried this code and it shows me data from database.
Hey I'm giving answer to bit old question but it may help someone if having same issue like #Rocky Rock and me.
Additionally I've to handle a large number of rows say 50,000 to 1,00,000. So I even tried some other solutions like chunking my result and tried to export into csv etc etc.
I also tried everything with force download with header and $writer->writeToStdOut(); but every logic goes into the vain.
But finally after day or two work around I coded as give and get rid of everything, believe me it can also download 1,00,000 rows in merely 20 seconds..
This is my code so instead of session variables of query and filename you can use whatever you like. Also I'd put some dummy variable as it is for one of our client.
<?php
include your required libraries..
include_once("lib/xlsxwriter.class.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Download IDs</title>
</head>
<body>
<?php
$sqlsel = $_SESSION['rptQry'];
$ressql = mysqli_query($sqlsel);
$currentdt = date('Ymdhis');
$filename = $currentdt."_".$_SESSION['rptFileName'];
$header = array(
'Header1'=>'integer',
'Header 2'=>'integer',
'Header 3'=>'string',
'Header 4' =>'string'
);
$dataArray = array();
$writer = new XLSXWriter();
$writer->setAuthor('Adaptable Services');
$writer->writeSheetHeader('ExportedIDs', $header);
while($res = mysqli_fetch_array($ressql)){
$writer->writeSheetRow('Sheet1',$res);
}
$writer->writeToFile('/var/www/html/tmpxls/'.$filename);
echo '<script>location.href="www.example.com/tmpxls/'.$filename.'";</script>';
?>
</body>
</html>
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.
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;
}
I'm working on a job app at work. It works great for everything except when the job applicant pushes the return button in the text fields. I have a field asking for their work history. So they enter company name [then pressed enter] address [then pressed enter] what they did for work [then pressed enter].
When the csv is exported it does this:
1|John|Smith|company name
address
what they did
2|Amy|Doe|company name
How can I make it do this:
1|John|Smith|company name|address|what they did|2|Amy|Doe|company name
This is the CSV generator:
// Fetch Record from Database
$output = "";
$table = "job_seeker"; // Enter Your Table Name
$sql = mysql_query("select seek_id, f_name, m_intial, l_name, add1, add2, city, state, zip, country, cell_num, home_num, email, app_position, app_workhist from $table WHERE $SER");
$columns_total = mysql_num_fields($sql);
// Get The Field Name
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= ''.$heading.'|';
}
$output .="\r\n";
// Get Records from the table
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .=''.$row["$i"].'|';
}
$output .="\r\n";
}
// Download the file
$date_st = "" . date("Y-m-d") . "";
$filename = "".$date_st."_exportall.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
As you can see I'm trying to get rid of the carriage return by mysqli_real_escape_string:
$app_workhist = mysqli_real_escape_string($con, $_POST['history']);
I've tried some "cleanup script". That didn't work either. Am I Doing some thing wrong. I would appreciate any help.
I was able to fix it by using a str_replace()
str_replace(array("\r\n","\r"),"",$string);
I am exporting result of a query in a csv file. The code is as shown below:
$query = "SELECT DATE(punchdetails.punchin) as punchday,punchdetails.punchin,punchdetails.punchout,employeedetails.employeename
FROM punchdetails join(employeedetails) ON punchdetails.employeeid=employeedetails.employeeid
AND punchdetails.employeeid=$employeeid AND DATE(punchdetails.punchin)=$fromdate";
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
ini_set('display_errors',1);
$private=1;
error_reporting(E_ALL ^ E_NOTICE);
$select_c = mysql_query($query);
while ($row = mysql_fetch_array($select_c))
{
$intime = strtotime($row['punchin']);
$mysqlintime = date( 'H:i:a', $intime );
$outtime = strtotime($row['punchout']);
$mysqlouttime = date( 'H:i:a', $outtime );
$result.=$row['employeename'].','.$row['punchday'].','.$mysqlintime.','.$mysqlouttime;
$result.="\n";
echo $result;
}
When I execute the query it is returning records correctly. But when I download the result of the query as csv file, the records are getting duplicated. I am getting the resultant csv file data as shown below:
Sonu,2013-09-26,10:55:am,11:12:am
Sonu,2013-09-26,10:55:am,11:12:am
Kristo,2013-09-26,11:23:am,11:24:am
I am not getting what is the problem. Can anybody help me to solve this? Thanks in advance.
I see the problem
you concatinate the result with each row, then echo. So, each time you echo - you will echo all the previous results + the current result.
Either, change:
$result.=$row['employeename'].','.$row['punchday'].','.$mysqlintime.','.$mysqlouttime;
$result.="\n";
to:
echo $row['employeename'].','.$row['punchday'].','.$mysqlintime.','.$mysqlouttime;
echo "\n";
or move the echo $result; outside the while loop
You need to echo $result outside of the while loop:
$result='';
while ($row = mysql_fetch_array($select_c))
{
$intime = strtotime($row['punchin']);
$mysqlintime = date( 'H:i:a', $intime );
$outtime = strtotime($row['punchout']);
$mysqlouttime = date( 'H:i:a', $outtime );
$result.=$row['employeename'].','.$row['punchday'].','.$mysqlintime.','.$mysqlouttime;
$result.="\n";
}
echo $result;