So, I'm using MPDF to export data/content from one textarea. It works perfectly fine for one textarea, but what happens when I need to export multiple texboxes with a button click? Doing it this way (as shown below) it only exports the last textarea only. I need your help to figure this out how to export from multiple textareas. Thank you.
My form.
The textareas with its content is being echoed/displayed using a while loop as shown below.
<form method='post' action='thanks.php' enctype="multipart/form-data">
<?php
while ($rows = mysqli_fetch_assoc($result)) {
?>
<textarea name="editor" id="editor">
<?= $rows['Content']; ?>
</textarea><br>
<input type="submit" name="export" value="Export" id="export" class="btn third">
<?php
}
?>
</form>
Export coding.
<?php
require_once __DIR__ . '/vendor/autoload.php';
if ((isset($_POST['editor'])) && (!empty($_POST['editor']))) {
$pdfcontent = $_POST['editor'];
$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML($pdfcontent);
// $mpdf->SetDisplayMode('fullpage');
// $mpdf->list_indent_first_level = 0;
//output in browser
$mpdf->Output('mypdf.pdf', 'D');
}
?>
You have to give each textarea another name, so each one gets included when you submit the form. One way of doing this is to use a counter:
<form method='post' action='thanks.php' enctype="multipart/form-data">
<?php
$areaCount = 1;
while ($rows = mysqli_fetch_assoc($result)) {
echo '<textarea name="editor_' . $areaCount . '" id="editor">'.
$rows['Content'] . '</textarea><br>';
$areaCount++;
}
?>
<input type="submit" name="export" value="Export" id="export" class="btn third">
</form>
Now when the form is submitted you have to find all the areas again:
<?php
require_once __DIR__ . '/vendor/autoload.php';
if (isset($_POST['export'])) {
$pdfcontent = '';
$areaCount = 1;
while (isset($_POST['editor_' . $areaCount])) {
$pdfcontent .= $_POST['editor_' . $areaCount];
$areaCount++;
}
$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML($pdfcontent);
// $mpdf->SetDisplayMode('fullpage');
// $mpdf->list_indent_first_level = 0;
//output in browser
$mpdf->Output('mypdf.pdf', 'D');
}
?>
Related
I am using php I have a product list page that gets the products from the database and displays it to the user. The user then chooses the quantity.
the problem is that i don't know how to display total price in the same page. As the next page is the one that calculates the total price.
Can anyone help me?
The main problem i am facing is when i am changing the quantity it is resetting the page so the quantity becomes 0. and i need post to work because its being calculated in another page.
include 'Accessories.php';
include_once 'Database.php';
session_start();
$db = new Accessories();
$accessories = $db->getAllAccessories();
echo 'second time';
echo '<br>';
echo '<br>';
echo '<br>';
echo '<form action=" '?> <?php $_SERVER['PHP_SELF']?> <?php echo'" method="post">';
echo '<div class="row"><div class="col-md-1"></div><div class="col-md-10"><input type="submit" name="submited" value="Procced" class="btn btn-block btn-primary"></div></div>';
echo '<div class="container">';
foreach ($accessories as $ac) {
echo
'<div class = "form-group">
<label for="qty_list[' . $ac->taskID . "-" . $ac->taskID . ']">'.$ac->taskName . " " . " " . $ac->description . " " . $ac->price . " BHD".'</label>';
echo '
<input id="" type="number" min="0" onchange="this.form.submit()" class="form-control" name="qty_list[' . $ac->taskID . "-" . $ac->taskID . ']" value="' ?> <?php $_POST['qty_list'] ?> <?php echo'" placeholder="">';
echo'</div>';
echo'<br>';
}
'</div>
</div>
</div>';
echo '</form>';
<?php
session_start();
include_once 'Database.php';
include 'Ac_car_res.php';
include 'Accessories.php';
include 'Reservation.php';
$reserved = false;
//$dateFrom = $_SESSION['dateFrom'];
//$dateTo = $_SESSION['dateTo'];
//echo $dateFrom;
foreach ($_POST['qty_list'] as $key => $qty) {
$r = 102;
//$_SESSION['resId'] = $r;
$qty;
$acAdd = new Ac_car_res();
// session_start();
$resId = $r;
$index = strrpos($key, "-");
$sCarId = substr($key, $index + 1);
$acId = substr($key, 0, $index);
$acAdd->initWith($acId, $resId, $sCarId, $qty);
$acAdd->addAcCarRes();
}
$db = Database::getInstance();
$access = new Accessories();
$res1 = new Reservation();
//echo $Id;
echo "<br>";
$r = 102;
$sql = "select * from ac_car_res where resId=" . $r;
$a = $db->multiFetch($sql);
foreach ($a as $m) {
$access->initWithAcId($m->acId);
$res1->initWithResId($m->resId);
echo "accessories" . $access->getPrice() . "qty" . $m->qty;
echo "<br>";
$totalPriceForRes = ($res1->getTotalPrice() + $access->getPrice() * $m->qty);
$res1->setTotalPrice($totalPriceForRes);
echo $res1->getTotalPrice();
echo "<br>";
$res1->updateReservation();
}
?>
<?php
session_start();
include_once 'Database.php';
include 'Ac_car_res.php';
include 'Accessories.php';
include 'Reservation.php';
$reserved = false;
//$dateFrom = $_SESSION['dateFrom'];
//$dateTo = $_SESSION['dateTo'];
//echo $dateFrom;
foreach ($_POST['qty_list'] as $key => $qty) {
$r = 102;
//$_SESSION['resId'] = $r;
$qty;
$acAdd = new Ac_car_res();
// session_start();
$resId = $r;
$index = strrpos($key, "-");
$sCarId = substr($key, $index + 1);
$acId = substr($key, 0, $index);
$acAdd->initWith($acId, $resId, $sCarId, $qty);
$acAdd->addAcCarRes();
}
$db = Database::getInstance();
$access = new Accessories();
$res1 = new Reservation();
//echo $Id;
echo "<br>";
$r = 102;
$sql = "select * from ac_car_res where resId=" . $r;
$a = $db->multiFetch($sql);
foreach ($a as $m) {
$access->initWithAcId($m->acId);
$res1->initWithResId($m->resId);
echo "accessories" . $access->getPrice() . "qty" . $m->qty;
echo "<br>";
$totalPriceForRes = ($res1->getTotalPrice() + $access->getPrice() * $m->qty);
$res1->setTotalPrice($totalPriceForRes);
echo $res1->getTotalPrice();
echo "<br>";
$res1->updateReservation();
}
?>
As you tagged, you need to use ajax, I will use jQuery because it's straight forward.
Presumably your first snippet is your select item page, but before that, I would maybe create an autoloader in a config file that gets include on every top-level page:
/config.php
<?php
define('DS', DIRECTORY_SEPARATOR);
# Set the root directory
define('ROOT_DIR', __DIR__);
# I would put classes in this folder instead of root
define('VENDOR', ROOT_DIR.DS.'vendor');
# Create a class autoloader so you don't have to manually include files for classes
spl_autoload_register(function($class){
# If you have classes in the root
$root = ROOT_DIR.DS.$class.'.php';
# See if there are any in vendor folder
$vendor = VENDOR.DS.$class.'.php';
# Check both folders, include if available
if(is_file($root))
include_once($root);
elseif(is_file($vendor))
include_once($vendor);
});
# Start session here, then you only ever have to write it once, provided you always
# include this config on the top level page at the top
session_start();
/product_list_page.php
<?php
# Add config
require(__DIR__.DIRECTORY_SEPARATOR.'config.php');
# Create instances
$db = new Accessories();
$accessories = $db->getAllAccessories(); ?>
second time<br><br><br>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<div class="row">
<div class="col-md-1">
<div class="col-md-10">
<input type="submit" name="submited" value="Procced" class="btn btn-block btn-primary" />
</div><!-- close col-md-10 -->
</div><!-- close col-md-1 -->
<div class="container">
<?php foreach($accessories as $ac): ?>
<div class="form-group">
<label for="qty_list[<?php echo $ac->taskID . "-" . $ac->taskID; ?>]"><?php echo $ac->taskName . " " . " " . $ac->description . " " . $ac->price . " BHD" ?></label>
<input id="" type="number" min="0" class="form-control" name="qty_list[<?php echo $ac->taskID . "-" . $ac->taskID ?>]" value="<?php echo $_POST['qty_list'] ?>" placeholder="" />
</div><!-- close form-group -->
<br>
<?php endforeach ?>
</div><!-- close container -->
</div><!-- close row -->
</form>
<!-- value will returned to this div -->
<div id="total-value"></div>
<script>
// Make sure to add the jquery library link
$(function(){
// Use a listener instead of inline javascript
$('form').on('change',function(e){
$.ajax({
// This page will process the form and calculate total
'url': '/calculate.php',
// Send via post
'type': 'post',
// Serialize the data
'data': $(this).serialize(),
// If/when the response from calculate is successful
'success': function(response) {
// Put that total into the blank div in the above html
$('#total-value').html(response);
}
});
});
});
</script>
/calculate.php
<?php
# Include config
include(__DIR__.DIRECTORY_SEPARATOR.'config.php');
/**
* Do your total calculations here based on POST then echo the final number. Whatever is
* echoed on this page will show up in the other page inside the "total-value" div
*/
I want to pass values from my php code (in the same page) to my html - so I could print it out nicely
here is my php function (it's in a while cause it needs to print out 3 lines from a text)
if(sizeof($words)==1)
{
$single = new single;
$docres = $single->find($words);
$dir = "source";
foreach ($docres as $key=>$filename) {
$counter = 0;
$file = $filename +1;
$handle = fopen($dir."/".$file.'.txt',"r");
if($handle)
{
while($counter < 3)
{
echo fgets($handle);
//this is what i need to print in my html
$input = $_POST['input'];
$counter++;
}
}
}
}
and here is my html
<html>
<head>
<title>serach engine</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<form action="" method="POST">
<center>
<h1> My Search Engine </h1>
<input type = 'text' size='90' value='' name = 'search' > <br>
<input type = 'submit' name = 'submit' value = 'Search source code' >
// <input type="value" name="input" value="<?php echo $input; ?>">
</center>
</form >
//I would like to print it out here
</div>
</body >
</html >
I searched over the web and saw a solution using $_POST but it didn't work for me...
You could just append it to a new variable and echo it out in the html.
For example:
while($counter < 3) {
echo fgets($handle);
//this is what i need to print in my html
$input .= $_POST['input'] . "<br />";
// You could also do:
// $input .= "<li>" . $_POST['input'] . "</li> "
// For a list item
$counter++;
}
And then echo it in the html:
</form>
<?php echo $input; ?>
</div>
Note: You did not increment your $counter in the while loop.
I have a table form which has a add new row button which upon clicked adds a new row to the table. I am trying to save all the rows in MySQL on clicking save button.
The code I wrote saves only one row no matter how many row I add. Could someone please tell my what am I doing wrong.
I searched Google but couldn't get anywhere.
Here are my codes:
save.php
<?php
include('connection.php');
if(isset($_POST['submit'])){
$row_data = array();
foreach($_POST['category'] as $row=>$category){
$category = mysql_real_escape_string($category);
$itemName = mysql_real_escape_string($_POST['itemName'][$row]);
$brand = mysql_real_escape_string($_POST['brand'][$row]);
$model = mysql_real_escape_string($_POST['model'][$row]);
$sellingPrice = mysql_real_escape_string($_POST['sellingPrice'][$row]);
$row_data[] = "('$category','$itemName','$brand','$model','$sellingPrice')";
}
}
if(!empty($row_data)){
$insert_query = mysql_query("INSERT INTO sale(Category,ItemName,Brand,Model,SellingPrice) VALUES".implode(',', $row_data));
if(!$insert_query){
echo "Error: " . mysql_error();
}else{
echo "Data Saved Successfully";
}
}
?>
and this is my html form
<form name="form1" id="myForm" action="saveSale.php" method="post">
<tr class="cloneme">
<td><input type="text" name="category[]"></td>
<td><input type="text" name="itemName[]"></td>
<td><input type="text" name="brand[]"></td>
<td><input type="text" name="model[]"></td>
<td><input type="text" name="sellingPrice[]"></td>
</tr>
</tbody>
</table>
</div>
<div class="eventButtons">
<input type="submit" name="submit" id="submit" value="Save">
<input type="reset" name="reset" id="reset" value="Clear" class="btn">
</div>
</form>
You are inserting data outside the for loop so it inserts only the last row or data.. What you have to do is to place insert query within foreach or for loop
if(isset($_POST['submit'])){
$row_data = array();
for($i = 0 ; $i < count($_POST['category']);$i++){
$category = mysql_real_escape_string($_POST[$i]['category']);
$itemName = mysql_real_escape_string($_POST[$i]['itemName']);
$brand = mysql_real_escape_string($_POST[$i]['brand']);
$model = mysql_real_escape_string($_POST[$i]['model']);
$sellingPrice = mysql_real_escape_string($_POST[$i]['sellingPrice']);
$insert_query = mysql_query("INSERT INTO sale(Category,ItemName,Brand,Model,SellingPrice) VALUES ('$category','$itemName','$brand','$model','$sellingPrice')");
if(!$insert_query){
echo "Error: " . mysql_error();
}else{
echo "Data Saved Successfully";
}
}
}
As I dont have enough reputation I am adding my comment as answer.
Your code is fine. It should work. There might be problem while you are cloning the row, may be it is not getting added under the form tag. You can verify it by dumping the $row_data variable.
Please share your javascript code which makes clone of the row, it will help us to solve your problem.
You need to run your query in for loop by counting the array value using count($_POST['category'])
if(isset($_POST['submit'])){
$row_data = array();
for($i= 0; $i <count($_POST['category']);$i++){
$category = mysql_real_escape_string($_POST[$i]['category']);
$itemName = mysql_real_escape_string($_POST[$i]['itemName']);
$brand = mysql_real_escape_string($_POST[$i]['brand']);
$model = mysql_real_escape_string($_POST[$i]['model']);
$sellingPrice = mysql_real_escape_string($_POST[$i]['sellingPrice']);
$insert_query = mysql_query("INSERT INTO sale(Category,ItemName,Brand,Model,SellingPrice) VALUES ('$category','$itemName','$brand','$model','$sellingPrice')");
if(!$insert_query){
echo "Error: " . mysql_error();
}else{
echo "Data Saved Successfully";
}
}
}
I have following code:
<?php
include_once 'init/init.funcs.php';
$pollid=(int) $_GET['pollid'];
$questions = array();
$result = mysql_query('SELECT kysimus FROM kysimused where kysimustik_id="' . $pollid . '"');
while($row = mysql_fetch_assoc($result)) {
$questions[] = $row['kysimus'];
}
$count=count($questions);
$x=0;
while ($x<$count){
echo $questions[$x];
$x+=1;
}
?>
<form method="get">
<input type="submit" value="Submit">
</form>
It takes the questions from the database which have kysimustik_id=poll_id and echos them out. But how could I make it work so questions will appear one at the time and new one appears only after I click "Submit" button?
You can do like the following
<div class="row text-center">
<button type="submit" class="btn btn-lg btn-info">Click Here!</button>
</div>
$(function(){
var values = [
"hi",
"hello",
"nice",
"wonderful"
];
var counter = 0;
$(".btn-lg").on("click", function(){
if(values.length) {
counter = (counter + 1) % values.length;
$('.row.text-center').append(values[counter] + ' ');
}
});
});
In the above example I have used javascript array. you can easily replace it by your php array
<?php
include_once 'init/init.funcs.php';
$pollid=(int) $_GET['pollid'];
if(isset($_POST['QuestionID'])
{
$questionID = $_POST["QuestionID"];
HandleAnswer($pollid,$questionID,$_POST['Answer']);
}
else
{
$questionID = 0;
}
$questions = array();
$result = mysql_query('SELECT kysimus FROM kysimused where kysimustik_id="' . $pollid . '"');
while($row = mysql_fetch_assoc($result)) {
$questions[] = $row['kysimus'];
}
function HandleAnswer(string PollId, string QuestionID, string Answer){
// Implement piece of code that sets the answer in the database,
// I leave this up to you since i have no Idea how your database is structured
}
$questionID++;
$count=count($questions);
if($questionID < $count){
?>
<form method="post" action="mypage?=<?php echo $pollid; ?>">
<?php echo $questions[$questionID]; ?>
<input type="hidden" name="questionID" value="<?php echo $questionID;?>"/>
<input type="text" name="Answer"/>
<input type="submit" value="Submit">
</form>
<?php }else{ ?>
THese were all our questions, thank you for answering!
<?php } ?>
I didn't test the code myself, but I'm pretty sure it works. Note that this is a hightly unsafe way to do this, because you can edit the value of the hidden field with extensions such as firebug.
Hey this problem may look really easy to solve but i can't find any solution, my dropdown isn't saving
<?php
// the relative path to the file
$fname = "Erros1.txt";
$fname2 = "Comentarios.txt";
// read in the file if present
if(file_exists($fname)) $txt = file_get_contents($fname);
if(file_exists($fname2)) $Comentarios = file_get_contents($fname2);
// if the user pushes the submit button
if(isset($_POST["Comentarios"])){
$Comentarios = $_POST["Comentarios"]; // get the entered content
file_put_contents($fname2,$Comentarios); // write the content to the file
}
if (isset($_POST["dropdown"])) {
// cast to integer to avoid malicious values
$dropdown = (int)$_POST["dropdown"];
}
?>
<form method="post" action="#">
<textarea name = "txt" cols = "120" rows = "20">
<?php echo $txt; ?>
</textarea>
<textarea name = "Comentarios" cols = "120" rows = "10">
<?php echo $Comentarios; ?>
</textarea>
// here is the dropdown
<select name="dropdown";>
<?php
for ($x=1; $x<=4; $x++) {
echo '<option value="' . $x . '">' . $x . '</option>' . PHP_EOL;
}
echo $_POST['dropdown']
?>
</select>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
Only my Comentarios Box is saving, maybe i need to change the submit or create another form