Exporting html (mysql populated) table to excel file - php

I am trying to query a mysql database and display data in a table. That part is working. At the moment, it is set up for displaying the
results within the certain date range.
I now want to take the table and make a button that allows you to export it to an Excel file. Before I added the option of choosing a date range, you were able to export to Excel, but now it seems that the second file does not know what table I am talking about. I tried using POST to send the values of the data and re-query on the other page.
When I click the button to export, the excel document that is downloaded is empty, (though it has a size). Any help please?
-----Query mysql---------
<html><head><title>New Production Rejections</title></head></html>
<?php
include("config.php");
//get serial from submitted data
//$serial = $_POST['sNumber'];
//if the submitted data is empty
$serial = $_POST['entryDate'];
$dateEnd = $_POST['entryDate2'];
//parse the serial from the link in tracker
?>
<form method="post" action="<?php echo "queryNewProdRejections.php?"?>">
Search between dates: (Format: YYYY-MM-DD)<input type='text' size='20' maxlength='20' name='entryDate'> - <input type='text' size='20' maxlength='20' name='entryDate2'>
<input type="submit" value="Search Date Range"><br/></form>
<?php
//query based on approved date that is nothing, repaired date that is nothing,
//tech is a real tech, location that is not Revite (RVP), action was to replace,
//and the status is not (declined or skipped).
$query = "SELECT *
FROM `rma`
WHERE `origin` NOT LIKE 'Field_failure'
AND `origin` NOT LIKE 'DOA_at_Customer'
AND `origin` NOT LIKE 'Sweden_Fail_VI'
AND `entry` > '$serial' AND `entry` < '$dateEnd'";
$data = mysql_query($query) or die(mysql_error());
//Create a table with the array of data from repairs, based on the previous query
echo "<table border='1'><tr><th>RMA</th><th>Product</th><th>Serial</th><th>Origin</th><th>Return To</th><th>Credit Num</th><th>Order</th><th>Entry Date</th><th>Tech</th><th>Traking Num</th></tr>";
while($row = mysql_fetch_array($data)){
print "<tr><td>".$row['intrma']."</td><td>".$row['product']."</td><td>".$row['serial']."</td><td>".$row['origin']."</td><td>".$row['retto']."</td><td>".$row['creditnum']."</td><td>".$row['ordernum']."</td><td>".$row['entry']."</td><td>".$row['tech']."</td><td>".$row['tracknum']."</td></tr>";
}
print "</table>";
?>
<html>
<form method="post" action="saveQueryToExcel.php">
<input type='hidden' name='ent_1' value="<?php echo $_POST['entryDate']; ?>">
<input type='hidden' name='ent_2' value="<?php echo $_POST['entryDate2']; ?>">
<input type="submit" value="Save to Excel">
</form>
</html>
---------------Print to Excel File -- (saveQueryToExcel.php)
<html><head><title>New Production Rejections</title></head></html>
<?php
error_reporting(0);
$dateBeg=$_POST['ent_1'];
$dateEnd=$_POST['ent_2'];
//Connect to the database, repairs in maprdweb
include("config.php");
//query based on approved date that is nothing, repaired date that is nothing,
//tech is a real tech, location that is not Revite (RVP), action was to replace,
//and the status is not (declined or skipped).
$query = "SELECT *
FROM `rma`
WHERE `origin` NOT LIKE 'Field_failure'
AND `origin` NOT LIKE 'DOA_at_Customer'
AND `origin` NOT LIKE 'Sweden_Fail_VI'
AND `entry` > '$dateBeg' AND `entry` < '$dateEnd'";
$data = mysql_query($query) or die(mysql_error());
//Create a table with the array of data from repairs, based on the previous query
header('Content-type: application/vnd.ms-excel');
echo "<table border='1'><tr><th>RMA</th><th>Product</th><th>Serial</th><th>Origin</th><th>Return To</th><th>Credit Num</th><th>Order</th><th>Entry Date</th><th>Tech</th><th>Traking Num</th></tr>";
while($row = mysql_fetch_array($data)){
print "<tr><td>".$row['intrma']."</td><td>".$row['product']."</td><td>".$row['serial']."</td><td>".$row['origin']."</td><td>".$row['retto']."</td><td>".$row['creditnum']."</td><td>".$row['ordernum']."</td><td>".$row['entry']."</td><td>".$row['tech']."</td><td>".$row['tracknum']."</td></tr>";
}
print "</table>";
?>

PHPexcel works great for exporting data to an actual Excel document.
It appears you are just generating an HTML table with your result.. which isn't exactly Excel format.

You should take the same code, and instead of printing <tr> lines with it, send it to fputcsv. Use the standard output as the file handle. You need to set proper html headers for the output to be sent as a csv, along the lines of this post: force file download.

Take a look a this class. It is able to solve the problem.
https://github.com/GSTVAC/HtmlExcel
$xls = new HtmlExcel();
$xls->addSheet("Names", $names);
$xls->headers();
echo $xls->buildFile();

Related

While loop - Only one input from many others is sending a value through POST

This is the code where I get my input names and values from a table called optionale and doing something with these:
<form role="form" autocomplete="off" action="includes/functions/fisa-init.php" method="POST">
<?php
connectDB();
$query = mysqli_query($mysqli, "SELECT * FROM `optionale`") or die(mysqli_error($mysqli));
while($row = mysqli_fetch_array($query))
{
?>
<span><?php echo $row['denumire']; ?></span>
<input type="text" name="nrBucati">
<input type="hidden" value="<?php echo $row['cod']; ?>" name="codProdus">
<?php } ?>
</form>
The optionale table looks like this:
The HTML looks like this:
As you can see in the last picture, I have in HTML, a name for input (taken from optionale table) and the actual input in which I write a value.
fisa-init.php:
$stmt3 = $mysqli->prepare("
UPDATE
`stocuri`
SET
`cantitate` = `cantitate` - ?
WHERE `cod` = ?
");
$stmt3->bind_param("is", $bucata, $cod);
// set parameters and execute
$bucata = mysqli_real_escape_string($mysqli, $_POST['nrBucati']);
$cod = mysqli_real_escape_string($mysqli, $_POST['codProdus']);
if (!$stmt3->execute())
{
echo "Execuția a întâmpinat o eroare: (" . $stmt3->errno . ") " . $stmt3->error;
}
$stmt3->close();
$mysqli->close();
In the code above (fisa-init.php) I am trying to take all the input values from my HTML and update rows in another table called stocuri:
As you can see, only the second row from stocuri table was updated, but I wrote values in all 5 inputs. It got only the last input.
How to modify the while loop in order to take all my inputs value?
If something is not clear, I apologize a hundred times. I will explain all the informations that are needed.
P.S. cod in table optionale is the same with cod in table stocuri. In this way, I know where to update values.
Each <input> MUST have an individual name or a named array.
So give each an aditional number like name1,name2 or use an named array like name[]
Finally this name="codProdus[]" is your solution.
Read more here
HTML input arrays
Have a nice day

Why are mySQL query results not displaying text from table when executed in PHP?

The below code is returning rows of checkboxes (the right number per the mySQL table) and with no error. The problem is that it is not grabbing the column values ((as per: ".$row['Zone'].": ".$row['RowNumber']. ))to place beside said checkboxes.
<?php
include'connect.php'
?>
<form method="post" action="chooseDate.php">
<?php
$sql = "
SELECT s.RowNumber, s.Zone,
FROM Seat AS s
LEFT JOIN Booking AS b, ON s.RowNumber = b.RowNumber,
AND b.PerfDate = ?,
AND b.PerfTime = ?,
WHERE b.RowNumber IS NULL,
GROUP BY s.RowNumber
";
$date = "$_POST[Date]";
$time = "$_POST[Time]";
$handle = $conn->prepare($sql);
$handle->execute(array($date, $time));
$res = $handle->fetchAll();
foreach($res as $row) {
echo "<input name='Seat' type='checkbox' value='".$row['Zone'].":
".$row['RowNumber']."'><br>";
}
?>
<input class="mybutton" type="submit" value="Choose Seat"/>
</form>
I have run queries using identical methods and they display the results as expected. The only difference here is that the query is LEFT JOIN. The results display in shell. This is a sample of the results and the expected output of one checkbox.
|**RowNumber**|**Zone**|
|-------------|--------|
|Z20 |box 4 |
Where am I going wrong? Thanks in advance.
Have you looked at the HTML output? You put the text inside the input element. The closing > is after the text.
You could fix that simply by just moving the > to the front, but I think it's bettter to generate a <label> element after the checkbox or surrounding the checkbox. If you give the checkbox an id, and the label a for attribute pointing to that id, the text is clickable too, which make an awesome UX. :)
So I suggest changing the for loop like this:
$idcounter = 0;
foreach($res as $row) {
$id = 'Seat' . ($idcounter++);
echo "<input name='Seat' type='checkbox' id='$id'><label for='$id'>".$row['Zone'].":".$row['RowNumber']."</label><br>";
}
Note that I removed the value attribute. I'm not sure if you would need it, but maybe you need both: the value and the label. If so you can put back that attribute like you had before, as long as you make sure to close the input element before opening the label.

Writing single page logging tool in php

Im making a small php webpage which I plan to use to track on which subjects a helpdesk receives calls. My database has 3 important fields: id, name, and amount for each subject.
On my page I have a form with a dropdown list where you select a type of call and click submit. The idea is that every time you click submit the page reloads and the amount in the database for the chosen id is heightened by 1.
The form gives me the id and name for each call:
<form method="post" action="index.php">
<select class="select" id="calltype" name="calltype">
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<option value=".$row["ID"].">".$row["NAAM"]."</option>".PHP_EOL;
}
}
?>
</select></br>
<input class="input" type="submit" name="Submit" value="Submit">
</form>
This part works, if I echo $_POST['calltype'] I get the correct ID. What I can't get to work is the update statement which I want to heighten the counter, like:
if(isset($_POST['calltype']{
mysqli_query("UPDATE calls SET amount=(amount+1), WHERE id = $_POST['calltype']");
}
How would I go about this? I tried several methods but can't get it to work
besides for the extra comma, interpolation with the POST array like this is risky. maybe try:
mysqli_query("UPDATE calls SET amount=(amount+1) WHERE id = " . mysqli_real_escape_string($link, $_POST['calltype']) . " ;");

Printing php page with various values

I have a php page that gets values from my database called print.php which I use to display and print the values from my database.
print.php?id=100 loads the page with values from the database that has the id 100. each record on my database has a field to store the date the record was created. As for now I visit print.php?id=100, print.php?id=101, print.php?id=102, print.php?id=103 and so on to print the same page but with various values.
Is there a way for me to create a button which does this automatically?
This button should grab all records that have the current date and print all those pages.
Sorry for being unclear.
My print.php page echos values from my database like this:
Id: <?php echo $info['id']; ?>
Name: <?php echo $info['name']; ?>
Date: <?php echo $info['date']; ?>
Gender: <?php echo $info['gender']; ?>
So for example visiting print.php?id=100 loads these values:
Id: 100
Name: John
Date: 2013-04-09
Gender: Male
Cisiting print.php?id=101 loads these values:
Id: 101
Name: Sarah
Date: 2013-04-09
Gender: Female
and so on.
When visiting each page I hit CTRL+P to print that information.
Instead of doing this manually (visiting each page and sending it to printer) I would like to have a script which grabs all the records of current date and sends it to my printer.
I'm not sure what you want to archieve, but I think you want a form like this:
<form method="get" action="">
<input type="text" name="id" value="100"/>
<input type="submit"/>
</form>
this would redirect the user to print.php?id=100 or with the value given in the textbox
EDIT:
What I read from the comments on the question is this what you want to archieve:
<form method="get" action="">
<input type="text" name="date" value="<?=date('yyyy-mm-dd');?>"/>
<input type="submit"/>
</form>
this would show a form with a textfield with the date of today printed in.
then you should make a query and fetch it like this:
$date = check_date($_GET['date']);
$query = 'SELECT * FROM values WHERE date="'.$date.'"';
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
// print row
}
}
the function check_date() is up to you to create, this checks if the text is a valid date to make sure nobody can hack your database
As I understand (it's not very clear) you want records for a specified date. Then you have to send a parameter for that date but not a single record id.
So, you can send a date with print.php?date=09-04-2013 for example and in you PHP script your query would be:
$date = $_GET['date']; // validate it
$sql = "SELECT * FROM table WHERE date = '$date'";
// fetch result
// print with a foreach loop as you like
Or if you want the current date only you don't need to pass a parameter at all. Just use CURDATE() if your date field contains only the date or NOW() if it contains date and time:
$sql = "SELECT * FROM table WHERE date = CURDATE()";
// fetch result
// print with a foreach loop as you like
More: https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
Still couldn't understand whether you have a problem with the HTML or with the PHP part.
If you are asking just for html forms and how to create a button you can check here:
http://www.w3schools.com/php/php_forms.asp
It's pretty simple to understand.

MySQL Not Working No Extracting Information?

I am working on a school project but I am having trouble with this block of code. Although I cant allow you guys to access my database, can you please try to find any syntax error or anything I am doing wrong. All I am getting is a blank space and any echoed text out of the loops.
<?php
$app= mysql_query("SELECT View FROM Stat");
echo "<table><tr>";
while($app_loop = mysql_fetch_array($app)){
$db_item = $app_loop['Item'];
$apps= mysql_query("SELECT * FROM Products WHERE Title='$db_item'");}
while($apps_loop = mysql_fetch_array($apps)){
$db_icon = $apps_loop['Icon'];
$db_title = $apps_loop['Title'];
echo"<td>
<form method='post' action='AppCatPage.php'>
<input type='image' src='$db_icon' width='50px' height='50px' id='sb'>
<input type='hidden' value='$db_title' name='apptitleu'>
</form>
</td>";
}
echo"</tr></table>";
?>
$app= mysql_query("SELECT View FROM Stat");
you selected only View column from table stat
$db_item = $app_loop['Item'];
but you are trying to read content of 'Item' Column
change first line to:
$app= mysql_query("SELECT * FROM Stat");
i think this is the problem ...

Categories