generate an Excel file using PHP - 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/

Related

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;

PHP not exporting MySQL database in right format

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.

Loading an image from a MySQL database with PHP

I have a question about loading an image from a MySQL database.
I have my database set up named 'demo' with one table 'contacts'. This has the 4 columns 'id', 'name', 'email' and 'image'. I can insert images with a HTML page I created. I also can achieve all my information with another HTML page I created, but the inserted BLOB images won't pop up, instead I see some huge bunch of characters (seems to besome encoding/decoding problem).
Heres the php-script that should get the data:
<?php
/*db information*/
$localhost="localhost";
$username="riko";
$password="QdTkCd12!";
$database="demo";
/*connect to database*/
mysql_connect($localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
/*prepare query*/
$query="SELECT * FROM contacts";
/*execute query*/
$result=mysql_query($query);
/*Number of rows delivered*/
$num=mysql_numrows($result);
/*Closing connection*/
mysql_close();
?>
<!-- Create a table to hold the data -->
<table border="1">
<tr>
<th>Image</th>
<th>Name</th>
<th>E-Mail</th>
</tr>
<?php
//Iterating over all rows in our table
$i=0;
while ($i < $num) {
//Get the first name, last name, mail and the image from the result
$first=mysql_result($result,$i,"first");
$last=mysql_result($result,$i,"last");
$email=mysql_result($result,$i,"email");
$data =mysql_result($result,$i,"image");
?>
<tr>
**HERE I WANT TO ECHO THE IMAGE INTO MY TABLE BUT I ONLY GET A BUNCH OF CHARACTERS**
<td><img src="<?php echo $data ?>" height="100" width="100"></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $first." ".$last; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif">E-Mail
</tr>
<?php
$i++;
}
?>
Can anyone tell me where my fault is? This is the php-script where I insert the images:
<?php
$localhost="localhost";
$username="riko";
$password="QdTkCd12!";
$database="demo";
$first=$_POST['first'];
$last=$_POST['last'];
$email=$_POST['email'];
mysql_connect($localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
// Make sure the user actually
// selected and uploaded a file
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$query = "INSERT INTO contacts VALUES ('','$first','$last','$email', '$data')";
mysql_query($query);
mysql_close();
}
header("Location: connect.php");
die();
?>
I really don't know what's wrong here.
I think you need to prefix the value in the src attribute with content information:
echo '<img src="data:image/png;base64,' . $data . '" />';
Make sure the database blob field contains base64 encoded data.

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!

Session Upload Progress & Multiple files

I am using this function here:
http://www.php.net/manual/en/session.upload-progress.php
And here is my code for the progress uploading:
<?
session_start();
$key = ini_get("session.upload_progress.prefix") . "myForm";
if(!empty($_SESSION[$key])) {
echo "<table width='400' style='font-family: Verdana; font-size: 12px;'>";
foreach($_SESSION[$key]['files'] as $f)
{
// Get percentage done
$current = $f["bytes_processed"];
$total = $f["content_length"];
if($current < $total) {
$done = ceil($current / $total * 100);
} else {
$done = 100;
}
echo " <tr>
<td colspan=2>{$f['name']}</td>
</tr>
<tr>
<td colspan=2><img src='uploading.gif' width='{$done}px' height='13px'></td>
</tr>
<tr>
<td>Started # ".date("H:m:s",$f['start_time'])."</td>
<td>{$done}%</td>
</tr>";
}
echo "</table>";
}
?>
The problem is that the individual files do not have a content_length variable. How can I work the progress for each file that is uploaded?
You can't, unless you're uploading a single file. $_SESSION[$key]['content_length'] is the total content length of the files that are being uploaded and the only indication of content length available. So you have two options: show a global progress of all files or limit the number of uploaded files to 1.
(Not sure if you are, but if you're willing to ditch this method you could opt for one of the numerous upload managers available. In the past I've used Fine Uploader with satisfaction.)

Categories