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;
Related
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);
//}
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>
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 have codes that should be getting value from mysql database, I can get only one value but I have while loop so it can get value and output data separated with comma. But I only get one value and cannot get multiple value. the result should be like this, // End main PHP block. Data looks like this: [ [123456789, 20.9],[1234654321, 22.1] ] here is the code:
<?php
// connect to MySQL
mysql_connect('localhost','','') or die("Can't connect that way!");
#mysql_select_db('temperature1') or die("Unable to select a database called 'temperature'");
if(ISSET($_GET['t']) && (is_numeric($_GET['t'])) ){
// message from the Arduino
$temp = $_GET['t'];
$qry = "INSERT INTO tempArray(timing,temp) VALUES(".time().",'$temp')";
echo $qry;
mysql_query($qry);
mysql_close();
exit('200');
}
// no temp reading has been passed, lets show the chart.
$daysec = 60*60*24; //86,400
$daynow = time();
if(!$_GET['d'] || !is_numeric($_GET['d'])){
$dayoffset = 1;
} else {
$dayoffset = $_GET['d'];
}
$dlimit = $daynow-($daysec*$dayoffset);
$qryd = "SELECT id, timing, temp FROM tempArray WHERE timing>='$dlimit' ORDER BY id ASC LIMIT 1008";
// 1008 is a weeks worth of data,
// assuming 10 min intervals
$r = mysql_query($qryd);
$count = mysql_num_rows($r);
$i=0;
$r = mysql_query($qryd);
$count = mysql_num_rows($r);
while($row=mysql_fetch_array($r, MYSQL_ASSOC)) {
$tid=$row['id'];
$dt = ($row['timing']+36000)*1000;
$te = $row['temp'];
if($te>$maxtemp) $maxtemp=$te; // so the graph doesnt run along the top
if($te<$mintemp) $mintemp=$te; // or bottom of the axis
$return="[$dt, $te]";
echo $return; //here I get all values [1385435831000, 21][1385435862000, 23][1385435892000, 22][1385435923000, 25][1385435923000, 22]
$i++;
if($i<$count) $return= ","; echo $return; // if there is more data, add a ',' however, it return me ,,,[1385435923000, 22]
$latest = "$dt|$te"; // this will get filled up with each one
}
mysql_close();
// convert $latest to actual date - easier to do it here than in javascript (which I loathe)
$latest = explode('|',$latest);
$latest[0] = date('g:ia, j.m.Y',(($latest[0])/1000)-36000);
?>
You're just assigning $return to the values from the last row your while loop grabbed instead of concatenating it. Try this
$return = "[";
while($row=mysql_fetch_array($r, MYSQL_ASSOC)) {
$tid=$row['id'];
$dt = ($row['timing']+36000)*1000;
$te = $row['temp'];
if($te>$maxtemp) $maxtemp=$te; // so the graph doesnt run along the top
if($te<$mintemp) $mintemp=$te; // or bottom of the axis
$return.="[$dt, $te]";
$i++;
if($i<$count) $return .= ", ";// if there is more data, add a ','
$latest = "$dt|$te"; // this will get filled up with each one
}
$return .= "]";
for some reason the Php date isn't working on the server.
Here is the function for displaying the tip of the day. I am using the codeigniter framework. In the function below i am trying to print the day of year ($doy). When i go to the url and try to access the tip function it shows a blank page. The day of year is not printed.
public function tip(){
$idCount = $this->db->query('SELECT Count(*) AS COUNT FROM clickmag_tip')->result();
$total = $idCount[0]->COUNT;
$time = time();
$doy = mdate('%z', $time);
echo $doy;
//$day_of_year = date('z',time());
//$doyear = date("z") + 1;
//echo $doyear;
$s = mktime(date("G") + 1);
print date("Y/m/d h:i:s a", $s);
if($total > 0){
$offset = $doy % $total ;
}
$data = $this->db->query('SELECT * FROM table_tip LIMIT 1 OFFSET '. $offset);
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode($data->result());
}
What do you think is the problem? I talked to the server people but they also don't know.
How can i solve this?
Thanks in advance!
You must output all headers before outputting anything.
You have both:
echo $doy;
AND
print date("Y/m/d h:i:s a", $s);
Before
header('Content-type: text/json');
header('Content-type: application/json');
That is what's causing the blank page.