PHP not exporting MySQL database in right format - php

so I am having trouble exporting the data from MySQL into excel
$output = '';
if(isset($_POST["export_excel"]))
{
$sql = "SELECT * FROM Logs ORDER BY item";
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0)
{
$output .= '
<table class="table bordered="1">
<tr>
<th>Sort</th>
<th>Unit Size</th>
<th>Quantity</th>
<th>Price per Unit</th>
<th>Time</th>
</tr>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["Sort"].'</td>
<td>'.$row["Unit Size"].'</td>
<td>'.$row["Quantity"].'</td>
<td>'.$row["Price per Unit"].'</td>
<td>'.$row["Time"].'</td>
</tr>
';
}
$output .= '</table>';
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=download.xls");
echo $output;
}
}
so when I hit the export button on my index.php page it outputs the data in this format: Google Sheets Link to the excel file
<table class="table bordered="1">
<tr>
<th>Sort</th>
<th>Unit Size</th>
<th>Quantity</th>
<th>Price per Unit</th>
<th>Time</th>
</tr>
<tr>
<td></td>
<td>45</td>
<td>0</td>
<td>0</td>
<td>2016-08-11 16:53:12</td>
</tr>
<tr>
<td></td>
<td>6</td>
<td>0</td>
<td>0</td>
<td>2016-08-11 16:53:12</td>
</tr>
</table>
so it outputs the right data but just the formating is off, here is what it looks like on the index.php page:
What the excel file should look like
do if anyone can tell me what I am doing wrong that be wonderful!
Thank you in advance!

Perhaps a little bit of a cheat outputting as csv rather than proper xls but it should more or less work.
<?php
if( isset( $_POST["export_excel"] ) ) {
ob_clean();
$sql = 'select * from logs order by item';
$result = mysqli_query( $connect, $sql );
if( mysqli_num_rows( $result ) > 0){
$delimiter=',';
$enclosure='"';
/* rather than create an actual file, use an output buffer and write to that */
$output=fopen('php://output','w+');
/* add column headers */
$headers=array( 'Unit Size', 'Quantity', 'Price_per_Unit', 'Time' );
/* write the headers to the output stream */
fputcsv( $output,$headers, $delimiter, $enclosure );
/* loop through recordset and add that to the stream */
while( $row = mysqli_fetch_array( $result ) ) {
fputcsv( $output, $row, $delimiter, $enclosure );
}
fclose( $output );
/* set the headers accordingly */
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=download.csv');
/* send the new content */
ob_flush();
}
}
?>

If i understand you correctly you want to export data into excel. In that case just changing the headers won't work because excel is not about table tags, What you need is a library for writing the contents into an excel format file and then make user download the same. Have a look at phpExcel.
You can also see in the example here on how to properly insert data in excel using the same.

Related

generate an Excel file using PHP

I'm new with PHP, I'm developping a WEB application that display a table with informations from an SQL server DATA BASE, the problem that I want to add a button to generate an EXCEL file that contains the table displayed? Is that possible??
#Ranjit this is the PHP code that displays the table and generate the excel file
edit 1
<?php
$ch="";
if(isset($_POST['historique']))
{
if ((!empty($_POST['Date_de_debut']))&& (!empty($_POST['Date_de_fin']))&&(!empty($_POST['Heure_de_debut']))&&(!empty($_POST['Heure_de_fin'])))
{
$ch= "(CONVERT(Datetime, '".$_POST['Date_de_debut']." ".$_POST['Heure_de_debut'].".000',120)) and (CONVERT(Datetime, '".$_POST['Date_de_fin']." ".$_POST['Heure_de_fin'].".000',120))";
?>
<table id="tab" border="1">
<tr>
<th><font color="red">Date</font></th>
<th><font color="red">Agent</font></th>
<th><font color="red">numéro</font></th>
</tr>
<?php
$search = " // my query
where operationDate between" .$ch;
$stmt = mssql_query($search);
while ($data = mssql_fetch_assoc($stmt))
{
?>
<tr>
<td><?php echo utf8_encode ($data['operationDate']);?></td>
<td><?php echo utf8_encode ($data['fullName']);?></td>
<td><?php echo utf8_encode ($data['number']);?></td>
</tr>
<?php
} }
?>
</table>
<?php
}
$output ='';
if(isset($_POST['excel']))
{
if ((!empty($_POST['Date_de_debut']))&& (!empty($_POST['Date_de_fin']))&&(!empty($_POST['Heure_de_debut']))&&(!empty($_POST['Heure_de_fin'])))
{
$rq = "// my query
where operationDate between" ."(CONVERT(Datetime, '".$_POST['Date_de_debut']." ".$_POST['Heure_de_debut'].".000',120)) and (CONVERT(Datetime, '".$_POST['Date_de_fin']." ".$_POST['Heure_de_fin'].".000',120))";
$res = mssql_query($rq);
if(mssql_num_rows($res)>0)
{
$output.='<table border=1>
<tr>
<th>Date</th>
<th>Depanneur</th>
<th>numéro</th>
</tr>
';
while ($row=mssql_fetch_array($res))
{
$output .='
<tr>
<td>'.$row["operationDate"].'</td>
<td>'.$row["fullName"].'</td>
<td>'.$row["number"].'</td>
</tr>';
}
$output .='</table>';
header("Content-Type: application/xls;charset=UTF-8");
header("Content-Disposition: attachement; filename=file.xls");
echo $output;
//mssql_close($conn);
}}}
?>
You'll have to select the data manually then insert them into the excel sheet, there's php library called PHPEXCEL you can use it.
See this
http://www.c-sharpcorner.com/article/export-to-excel-in-php-with-my-sql/
There are some nice packages out there to generate excel files such as
Box Spout and PHP Spreadsheet.
The documentation of both packages is very clear any you will be generating excel files within minutes of browsing through documentation.
Yes,
It is possible. You can follow this
1) Connect to database:
2) Define a filename of excel
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
$fp = fopen('database.xls', "w");
$schema_insert = "";
$schema_insert_rows = "";
//start of printing column names as names of MySQL fields
Sources - http://www.anillabs.com/2010/03/how-to-create-excel-file-with-mysql-data-using-php-code/

Export MySQL Data to MS Excel is working well in local but not on server

<title>Orders Export</title>
<body>
<?php
header('Content-Type: application/xls');
header('Content-Disposition: attachment; filename=download.xls');
$con = mysqli_connect('localhost','suresafe_admin','iwant$100','suresafe_suresafety');
$query = "select * from `orders_approval` where `approve`='1' and `company_name`='GAVL-F111'";
$result = mysqli_query($con,$query);
$output = '';
if(mysqli_num_rows($result) > 0)
{
$output .= '?>
<table class="table" bordered="1">
<tr>
<th>order_no</th>
<th>order_date</th>
<th>order_name</th>
<th>total_amount</th>
</tr><?php
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["order_no"].'</td>
<td>'.$row["order_date"].'</td>
<td>'.$row["order_name"].'</td>
<td>'.$row["total_amount"].'</td>
</tr>
';
}
$output .= '</table>';
}?>
</body>
</html>
The code is simple. Working well in local. But when I use this in my website on server. It shows only table with data. It don't export that data in Excel.
order_no order_date order_name total_amount
100000705 2017-05-07 MR. PRADEEP Y 113500
100000708 2017-05-11 MR. A SRINIVASA RAO 5448
100000725 2017-05-30 MR. A SRINIVASA RAO 77180
Here is the result I can see when I click on export link.
In local server, it is easily exported.
If you had configured your server properly, you would be seeing warnings. You cannot send a header after data has already been output. In addition, the data you're sending is not application/xls (which is not a valid MIME type) it's text/html. You're also outputting "?>" and "<?php" into your HTML, which will not work too well.
However, I would suggest going with CSV for the data you're outputting:
<?php
$con = mysqli_connect("localhost", "suresafe_admin", "iwant$100", "suresafe_suresafety");
$query = "SELECT order_no, order_date, order_name, total_amount from orders_approval WHERE approve = 1 AND company_name = 'GAVL-F111'";
$result = mysqli_query($con, $query);
$output = "";
if(mysqli_num_rows($result) > 0) {
$output .= "order_no,order_date,order_name,total_amount\n";
while($row = mysqli_fetch_assoc($result)) {
$output .= "$row[order_no],$row[order_date],$row[order_name],$row[total_amount]\n";
}
}
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=download.csv");
echo $output;

error generate pdf - PHP

This have been bugging me for a few hours. When i try to produce pdf, i got this error:
1) Warning: Division by zero in C:\xampp\htdocs\KPAPMS\PHP\lib\pdftable.php on line 540
2) FPDF error: Some data has already been output, can't send PDF file
i just use the existing code to generate pdf(fpdf).
this is my code example
<?php
$sql = "SELECT * from vesservice";
$res = mysql_query($sql);
$hdd= "<table width=100%>
<tr><th width=100><strong>Company</strong></th><th><strong>: Kuching Port Authority</strong></th><th></th>
<th>Date / Time: ".$date."</th></tr>
<tr><th width=100><strong>Title</strong></th><th><strong>: Water Supply for SCN</strong></th><th></th><th></th></tr>
<tr><th colspan=4><hr></th></tr>
<tr>
<th><strong>SCN</strong></th><th>:</th>
<th><strong>Berth Date</strong></th><th>:</th></tr>
<tr>
<th><strong>Debtor Code</strong></th><th>:</th>
<th><strong>Expected Depart Date / Time</strong></th><th>:</th></tr>
<tr>
<th></th><th></th>
<th><strong>Actual Depart Date / Time</strong></th><th>:</th></tr>
<tr><th colspan=4><hr></th></tr>
</table>";
$tables="<table width=100%>
<tr align=center>
<th>Service Reference</th>
<th>Service Code</th>
<th>Water Supply Reference</th>
<th>Water Supply Sequence</th>
<th>Tariff Code</th>
<th>Tariff Description</th>
<th>UOM</th>
<th>Service Date</th>
<th>Requested Time</th>
<th>Volume<br />(Tonne)</th>
<th>Service Date</th>
<th>Started Time</th>
<th>Volume<br />(Tonne)</th>
<th>Service Date</th>
<th>Ended Date</th>
<th>Duration</th></tr>";
while($rs=mysql_fetch_assoc($res))
{
$tables.= "<tr align=center>
<td>".$rs['serv_opt']."</td>
<td>".$rs['dt_code']."</td>
<td>".$rs['scn']."</td>
<td>".$rs['term_code']."</td>
<td>".$rs['serv_cat']."</td>
<td>".$rs['serv_code']."</td>
<td>".$rs['activ_cnt']."</td>
<td>".$rs['serv_date_req']."</td>
<td>".$rs['serv_shift_req']."</td>
<td>".$rs['serv_qty']."</td>
<td>".$rs['serv_ref']."</td>
<td>".$rs['res_serv_date']."</td>
<td>".$rs['res_serv_time']."</td>
<td>".$rs['new_serv_date']."</td>
<td>".$rs['new_serv_time']."</td>
<td>".$rs['new_serv_qty']."</td>
</tr>";
}
$tables.="</table>";
//echo $hdd.'<br />'.$tables;
$p = new PDFTable('L','mm','a4');//set page orientation P/L
$p->SetFont('Times','',10);
$p->headerTable=$hdd;
$p->AddPage();
$p->htmltable($tables);
//ob_end_clean();
$p->output("Water Supply.pdf",'I'); //D=download
When i uncommet the ob_end_clean, it can generate the pdf output, but only print $tables but the header is not printed.
Please help me, which part i did wrong.
You can try insert ob_end_clean(); before outputing.
Example
<?php
require('fpdf.php');
$pdf = new FPDF();
//your code for eneration of the pdf
ob_end_clean();
$pdf->Output();
?>
Ok if you want FPdf to work properly, there cannot be any output at all beside what fpdf generates. You can solve the problem deleting all new line characters found at the end of the .php files, using the following regular expression
\?>\n\z
replaced with
\?\n
For example:
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Ok, OK
$pdf->Output();
?>
But this won't work
<?php
echo "You don't sent before output";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'OK oK);
$pdf->Output();
?>

PHP Simple HTML DOM Parser works on localhost but not live WordPress website

I am working with a WordPress plugin that outputs a table of data on the plugin's admin page. I have modified the plugin to add a button on the page that exports the table of data into a CSV file. Everything works perfectly on my localhost, but after transferring to the live server, it no longer works - the CSV file that is exported is blank. I am using PHP Simple HTML DOM Parser to parse the HTML table and convert it to CSV, and this seems to be where the roadblock is happening.
I have added the export button with this code (parts of the URL hidden for privacy):
<form action="**website-url**/wp-content/plugins/**plugin**/includes/votes-logs-export.php" method="POST">
<input type="submit" value="<?php _e('Export Table as CSV','**plugin**'); ?>" class="button" id="export" name="export" />
</form>
My file votes-logs-export.php has this code:
require_once('../../../../wp-load.php');
include 'simple_html_dom.php';
$file_name = "contest_votes_".date('d-m-Y-H-i-s').'.csv';
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=".$file_name);
global $wpdb;
$export_sql = "SELECT log.*,pst.post_title FROM ".$wpdb->prefix."votes_tbl as log LEFT JOIN ".$wpdb->prefix."posts as pst on log.post_id=pst.ID ORDER BY pst.post_title DESC";
$export_logs = $wpdb->get_results($export_sql, OBJECT);
if (!empty($export_logs)) {
$fp = fopen("php://output", "w");
if ($wpdb->num_rows > 0) {
$output = '';
foreach ($export_logs as $logs) {
$vote_id = $logs->post_id;
$postdata = get_posts($vote_id);
$vote_author_id = $postdata[0]->post_author;
$vote_author = get_the_author_meta( 'display_name', $vote_author_id );
$voter_name = $logs->ip;
if(filter_var($voter_name, FILTER_VALIDATE_IP) !== false)
$voter_name = $logs->ip;
else
$voter_name = get_the_author_meta( 'display_name', $voter_name );
$voted_date = $logs->date;
$output .= '
<tr>
<td>'.$logs->post_title.'</td>
<td class="author column-author">'.$vote_author.'</td>
<td class="author column-author">'.$voter_name.'</td>
<td class="author column-author">'.$voted_date.'</td>
</tr>';
}
}
$table = '
<table>
<tr>
<th>Title</th>
<th>Author</th>
<th>Voter</th>
<th>Vote Date</th>
</tr>' . $output . '</table>';
$html = str_get_html($table);
foreach($html->find('tr') as $element){
$td = array();
foreach( $element->find('th') as $row){
$td [] = $row->plaintext;
}
// prevent blank rows being inserted into CSV file
if (!empty($td)) {
fputcsv($fp, $td);
}
$td = array();
foreach( $element->find('td') as $row){
$td [] = $row->plaintext;
}
// prevent blank rows being inserted into CSV file
if (!empty($td)) {
fputcsv($fp, $td);
}
}
fclose($fp);
}
I'm able to view the PHP page in order to debug by commenting out the header redirects. On my localhost, the PHP page outputs the table data in CSV format, but on the live server, it's a blank page. (No errors on the page or in error_log.) I have debugged this code and found that $table and all of the code above it seems to be running perfectly - if I print the contents of $table I get a formatted HTML table of my data:
<table>
<tbody>
<tr>
<th>Title</th>
<th>Author</th>
<th>Voter</th>
<th>Vote Date</th>
</tr>
<tr>
<td>Writing-on-Stone Park</td>
<td class="author column-author">admin</td>
<td class="author column-author">email#email.com</td>
<td class="author column-author">2014-07-04 16:42:57</td>
</tr>
<tr>
<td>White Tailed Ptarmigan</td>
<td class="author column-author">admin</td>
<td class="author column-author">email#email.com</td>
<td class="author column-author">2014-07-04 06:07:51</td>
</tr>
<tr>
<td>Rockbound Lake</td>
<td class="author column-author">admin</td>
<td class="author column-author">email#email.com</td>
<td class="author column-author">2014-07-04 06:07:28</td>
</tr>
</tbody>
</table>
The block happens at $html = str_get_html($table) - if I print out $html, nothing gets printed to the page, not even an error or any kind of 'false' or 'NULL' value. If I try to echo a string after that block of code, it is not output to the page, so the script seems to stop running there.
I was able to confirm that my simple_html_dom.php file is being referenced correctly because echoing a string in that file does get output to my votes-logs-export.php page. Yet the functions within the file don't seem to be firing? I'm out of ideas on this one!
I confirmed that 'allow_url_fopen' is set to 'true' in php.ini. In my simple_html_dom.php file, I also tried changing the "MAX_FILE_SIZE" from 600,000 to 100,000,000 but to no effect. The memory on the server is set to 40MB. I admit I am a newbie with working with custom WordPress plugins, but the fact this works on my localhost seems to indicate there is some kind of configuration or compatibility issue on the live server...? I would appreciate any guidance or tips you can offer.
PHP version on the live server is 5.4.21. My localhost is using 5.3.
I ended up explicitly setting error_reporting(1) in my file, which finally threw me a valuable error - Call to undefined function mb_detect_encoding() on line 1238 of simple_html_dom.php. Turns out I needed to enable the PHP extension mbstring on my server. Problem solved!

Why TCPDF result doesn't show if I have lof of data?

I have developed a software with PHP and report with TCPDF. It runs well, but after importing lot of data in MySQL, the PHP can't produce the report before the browser times out. I've tried with the latest firefox and Chrome versions.
This my script:
<?php
require_once('tcpdf/config/lang/eng.php');
require_once('tcpdf/tcpdf.php');
// create new PDF documentation
include "koneksi.php"; //file conection
$bln=$_POST[BLN]; //for catch month
$thn=$_POST[THN]; //for catch year
$exp=$_POST[EXP]; //for catch expedition name
if(empty($exp))
{
$sql = "SELECT * FROM tb_exp_local where bulan = '$bln' AND tahun = '$thn'";
}
elseif($exp != "")
{
$sql = "SELECT * FROM tb_exp_local where bulan = '$bln' AND tahun = '$thn' AND nama_exp = '$exp'";
}
$hasil = mysql_query($sql);
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set font
$pdf->SetFont('times', '', 11);
// landscape
$pdf->addPage( 'L', 'LETTER' );
//this for convert html to pdf with html function
$html = '
<table border="1" cellspacing="3" cellpadding="4">
<tr><td colspan="9" align="center"><h2>Form Pantauan Expedisi Export</h2></td></tr>
<tr>
<th align="center"><b>Tanggal</b></th>
<th align="center"><b>Nama Expedisi</b></th>
<th align="center"><b>Nama Distributor</b></th>
<th align="center"><b>Kota Tujuan</b></th>
<th align="center"><b>No Faktur</b></th>
<th align="center"><b>Kondisi Armada Pengiriman</b></th>
<th align="center"><b>Ketepatan Jumlah</b></th>
<th align="center"><b>Ketepatan Waktu Kirim</b></th>
<th align="center"><b>Keterangan</b></th>
</tr></table>';
while ($data = mysql_fetch_array($hasil))
{
$html .= '<table border="1"><tr><td align="center">'.$data['tgl'].'</td>
<td align="center">'.$data['nama_exp'].'</td>
<td align="center">'.$data['nama_dist'].'</td>
<td align="center">'.$data['kota_tujuan'].'</td>
<td align="center">'.$data['faktur'].'</td>
<td align="center">'.$data['konarmada'].'</td>
<td align="center">'.$data['tepatjml'].'</td>
<td align="center">'.$data['tepatwaktu'].'</td>
<td align="center">'.$data['ket'].'</td>
</tr></table> ';
}
$pdf->writeHTML($html, true, false, true, false, ''); //for generate
$pdf->Output('FormPantauExpLocalAll', 'I'); // for generate pdf file
?>
Server timeout does not depend on browser. Try using set_time_limit(60) inside your loop:
while ($data = mysql_fetch_array($hasil))
{
set_time_limit(60);
$html .= '(...)';
}
Also, try adding INDEX to your DB on (bulan, tahun, nama_exp) columns, it should speed up the retrieval process. Also, be aware that you may have run out of memory during the process (check your PHP logs on your server)

Categories