Manipulating HTML code with external PHP file called from a form - php

I want to write a basic form with inputs that executes an external php file. That file should do some calculations with the inputs and append the output to a table.
My HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Prices</title>
</head>
<body>
<form name="priceform" method="get" action="add-item.php">
<input name="item_name" placeholder="Item Name">
<input name="amount" placeholder="Amount">
<input name="price_per_unit" placeholder="Price per Item">
<button type="submit" name="submit">Submit</button>
</form>
<div id="pricetable">
<table>
<thead>
<tr>
<th>Name</th>
<th>Amount</th>
<th>Netto</th>
</tr>
</thead>
<tbody>
<!-- Append rows here -->
</tbody>
</table>
</div>
My PHP Code
<?php
$item_name = $_GET["item_name"];
$amount = $_GET["amount"];
$price_per_unit = $_GET["price_per_unit"];
//do calculations
echo "
<tr>
<td>$item_name</td>
<td>$amount</td>
<td>$price_per_unit</td>
</tr>";
?>
I want the table row to append to my table in the html file.
Thanks for the help in advance.

You can merge these files together, or if you want external php file, you can just call it like this:
index.php:
...
<div id="pricetable">
<table>
<thead>
<tr>
<th>Name</th>
<th>Amount</th>
<th>Netto</th>
</tr>
</thead>
<tbody>
<?php include "calculate.php";?>
</tbody>
</table>
</div>
...
calculate.php is that calculation php file.

You can do this in two ways:
save the previously added lines somewhere (session, database?) and load them each time you refresh the page, adding a new line at the end with new data (and of course, re-save them with this new data)
or each time send previously added lines in the form. So you need to add a lot of hidden values to the form in which all previously submitted values will be stored.

Related

Email value not showing using POST method

I have this form in which there is only one field i.e. "Email id", so what I have to do is that when I entered the email id the email id must be split into two parts like user name and domain name and must be displayed in next form.
So my problem is that my 2nd form doesn't display the result, however when I used $_SESSION method in place of $_POST(to take value of email field) it takes the value and also split it but takes only one value as I want to take multiple email ids.
For better understanding please check my code.
<?php
session_start();
?>
<!Doctype html>
<html>
<head>
<title>PHP3</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="jumbotron">
<div class="container">
<form class="form-horizontal" method="post" action="screen3_controller.php">
<div class="form-group">
<label class="control-label col-sm-2" for="email_text">Email:</label>
<div class="col-sm-10">
<input type="email" class="form-control" name="email_text" id="email_text">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" name="submit" id="submit_button" class="btn btn-default" value="Submit">
</div>
</div>
</form>
</div>
</div>
<table class="table table-striped table-responsive">
<thead>
<tr>
<th>Email Id</th>
</tr>
</thead>
<tbody>
<?php
if(isset($_SESSION['all_post']) && !empty($_SESSION['all_post']))
{
foreach($_SESSION['all_post'] as $key=>$value)
{
?>
<tr>
<td><?php echo $value['email_text']; ?></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
<div class="container">
<table class="table table-bordered">
<thead>
<tr>
<th>User Name</th>
<th>Domain Name</th>
</tr>
</thead>
<tbody>
<?php
$str = $_POST['email_text'];
$hello = explode("#", $str);
$_SESSION ['emails'] = $hello;
echo "<tr>";
foreach ($_SESSION ['emails'] as $value)
{
echo "<td>$value</td>";
}
echo "</tr>";
?>
</tbody>
</table>
</div>
</body>
</html>
Controller:
<?php
session_start();
$data = $_POST;
if (isset($data['submit'])) {
$_SESSION['all_post'][] = $data;
}
header('Location:screen3_2.php'); exit();
?>
As I can see,
In your code you are posting your form data to controller, not the second page.
Though you are storing your data to $_SESSION in your controller page, That's how you're able to access data from second page.
Solution :
either access data on second page using $_SESSION, or
POST your first page to directly second page, and access data using $_POST.
When the following code executes, it does NOT send the POST vars with it.
They are lost at that point. However, you have stored the data in the session.
header('Location:screen3_2.php'); exit();
Also note that the following code:
$str = $_POST['email_text'];
$hello = explode("#", $str);
$_SESSION ['emails'] = $hello;
Will store the two parts of exactly one email. You mentioned that you want to store multiple emails and this code will not accomplish that.
It seems to me that what you want to do is to keep going back to the same page and reusing the form while collecting email addresses. Please confirm.
Try this:
Do not use a separate controller file. Take that code and remove the redirect. Put that code at the top of the file. This way you collect
all the email addresses from $_POST.
<?php
// Taken from 'controller'
session_start();
// Only process post if it exists
if ( ! empty($_POST) ) {
$data = $_POST;
if ( isset($data['submit']) ) {
$_SESSION['all_post'][] = $data;
}
}
// No redirect
?>
<?php // put the form here ?>
<form class="form-horizontal" method="post" >
<input type="email" class="form-control" name="email_text" id="email_text">
<input type="submit" name="submit" id="submit_button" class="btn btn-default" value="Submit">
</form>
<?php
// output all the email addresses collected
if(isset($_SESSION['all_post']) && !empty($_SESSION['all_post'])) {
foreach($_SESSION['all_post'] as $key=>$value) {
$parts = explode('#', $value['email_text']);
?>
<tr>
<td><?= $parts[0] ?></td> <?php // before # ?>
<td><?= $parts[1] ?></td> <?php // after # ?>
</tr>
<?php
}
}
?>
</form>

Refreshing a textbox every couple of seconds with mysql query?

I have this textbox in my code that everytime this page is loaded/refreshed, its content is filled with a query result. But since refreshing manually is not an option in my case, how can I do this automatically (I only want to refresh the textbox)? I've read about using AJAX, and I've been reading about it, but to be honest I don't quite get how to make it work, could someone explain me and dumb it down? Isn't there any easier way to refresh the textbox with the query content?
EDIT: Okay, I think I understood the basics of AJAX, the function is now refreshing the textbox every second, but there's a small problem. It messed up my table big time. I've modified the HTML code in hope someone can tell me what I did wrong. I'm thinking I shouldn't be including a div inside a table?
Here's how my table looked like and how it looks like after this little update
<?php
include '../Login/db_login.php';
session_start();
$sql = "SELECT Contador FROM senhas2 WHERE ID=1";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$nome = $row['Contador']
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Página de administração - A</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
setInterval(function(){
$('#refreshtb').load('bt1admin.php');
}, 1000)
</script>
</head>
<body>
<form action="" id="atender" method="POST">
<table border="1">
<tr>
<td>Clientes em espera:</td>
<td><div id="refreshtb"><input id="refreshtb" type="text" value="<?php echo "$nome";?>"readonly></div></td>
</tr>
<tr>
<td>Selecionar posto de atendimento:</td>
<td><select name="posto"><option value="n1" selected>1</option><option value="n2">2</option><option value="n3">3</option><option value="n4">4</option><option value="n5">5</option><option value="n6">6</option></select>
</tr>
<tr>
<td colspan="2"><input type="submit" form="atender" name="atender" value="Atender Cliente Seguinte"></td>
</tr>
</table>
</form>
</body>
</html>
You cannot change the content of a page using PHP. You'll need to use a front-end language, such as Javascript. Javascript is able to change your page's content, even after it is loaded. In order to update your page's content every X seconds, you'll want to use Javascript's setInterval() function to run a function every X seconds. This function would use AJAX to send a request to your website and gather some more data, and then update your textbox to contain this new data. You might find this Stackoverflow question helpful: How does AJAX work?
EDIT: To clear up some confusion in our comment discussion and in response to your edits, I've modified your code a little bit. Try this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Página de administração - A</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
setInterval(function(){
$.ajax('bt1admin.php').done(function(data) {
$("#refreshtb").val(data);
})
}, 1000);
</script>
</head>
<body>
<form action="" id="atender" method="POST">
<table border="1">
<tr>
<td>Clientes em espera:</td>
<td><div><input id="refreshtb" type="text" value="<?php echo "$nome";?>"readonly></div></td>
</tr>
<tr>
<td>Selecionar posto de atendimento:</td>
<td><select name="posto"><option value="n1" selected>1</option><option value="n2">2</option><option value="n3">3</option><option value="n4">4</option><option value="n5">5</option><option value="n6">6</option></select>
</tr>
<tr>
<td colspan="2"><input type="submit" form="atender" name="atender" value="Atender Cliente Seguinte"></td>
</tr>
</table>
</form>
</body>
</html>
What I did:
First of all, you had duplicate #refreshtb elements, so I removed one of them.
You were also using the .load() method in JQuery. This does not update the value of an HTML input. Instead, it just replaces the child HTML, which is not what you want. I updated your script to now update the value of the #refreshtb input element.
Tested and it seems to work fine for me. If you're still getting that weird table issue after this or for some reason the field isn't being updated properly, I suspect it's an issue with your bt1admin.php page. Make sure that page isn't outputting the entire table, and instead just the value you want to go into the text box.

How to stop insert into after refreshing a page in php pdo

when i refresh page auto submit . how to stop insert data when page refresh ? i want insert data when click add button and without redirect another page.
plz help me. i want to came page display show data.
<?php
try{
$host='localhost';
$name='pdo';
$user='root';
$pass='';
$dbc = new PDO("mysql:host=$host;dbname=$name",$user,$pass);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
//---------------------------------------------------------------------
if (isset($_POST['add']))
{
$stmt = $dbc->prepare("insert into user (frist,last,web) values (:frist,:last,:web)");
$stmt->bindParam(':frist',$_POST['frist']);
$stmt->bindParam(':last',$_POST['last']);
$stmt->bindParam(':web',$_POST['web']);
$stmt->execute();
}
?>
<!DOCTYPE html>
<html>
<head>
<title> the digital craft - PDO</title>
</head>
<body>
<header>
<h1>Mysql PDO</h1>
</header>
<div>
<form method="post">
<input name="frist" placeholder="frist name">
<input name="last" placeholder="last name">
<input name="web" placeholder="web site">
<button name="add" type="submit">Add</button>
</form>
</div>
<hr>
<table>
<thead>
<tr>
<th>ID</th>
<th>Frist Name</th>
<th>Last Name</th>
<th>Website</th>
<th>Save</th>
</tr>
</thead>
<tbody>
<?php
$stmt=$dbc->query("SELECT * FROM user");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while($data=$stmt->fetch()){
?>
enter code here<tr>
<td><input name="id" value="<?=$data['id']?>"></td>
<td><input name="frist" value="<?=$data['frist']?>"></td>
<td><input name="last" value="<?=$data['last']?>"></td>
<td><input name="web" value="<?=$data['web']?>"></td>
<td><button name="save" type="submit">save</button></td>
</tr>
<?php } ?>
</tbody>
</table>
</body>
</html>
You could redirect the user to other/same page after submit logic has been run. After that, refreshing shouldn't submit the form again.
A little addition to what Siim said:
you can do this with header("Location: name_of_file.php"); after $stmt->execute();

Unable to access fetch dBase data. The login page keep looping back to thesame page

Each time i tried to log in through : webhost/adminlogin.php , am redirected back to thesame page. Is there any thing i forgot to add? Thank you for your help.. Here is my script below
This is my adminlogin.php
<?php session_start(); if(isset($_SESSION[ 'admin_login'])) header( 'location:admin_homepage.php'); ?>
<!DOCTYPE html>
<html>
<head>
<noscript>
<meta http-equiv="refresh" content="0;url=no-js.php">
</noscript>
<meta charset="UTF-8">
<title>Admin Login - Online Banking</title>
<link rel="stylesheet" href="newcss.css">
</head>
<?php include 'header.php'; ?>
<div class='content'>
<div class="user_login">
<form action='' method='POST'>
<table align="center">
<tr>
<td><span class="caption">Admin Login</span>
</td>
</tr>
<tr>
<td colspan="2">
<hr>
</td>
</tr>
<tr>
<td>Username:</td>
</tr>
<tr>
<td>
<input type="text" name="uname" required>
</td>
</tr>
<tr>
<td>Password:</td>
</tr>
<tr>
<td>
<input type="password" name="pwd" required>
</td>
</tr>
<tr>
<td class="button1">
<input type="submit" name="submitBtn" value="Log In" class="button">
</td>
</tr>
</table>
</form>
</div>
</div>
<?php include 'footer.php'; ?>
<?php include '_inc/dbconn.php'; if(!isset($_SESSION[ 'admin_login'])){ if(isset($_REQUEST[ 'submitBtn'])){ $sql="SELECT * FROM admin WHERE id='1'" ; $result=mysql_query($sql); $rws=m ysql_fetch_array($result); $username=m ysql_real_escape_string($_REQUEST[
'uname']); $password=m ysql_real_escape_string($_REQUEST[ 'pwd']); if($username==$rws[8] && $password==$rws[9]) { $_SESSION[ 'admin_login']=1; header( 'location:admin_hompage.php'); } else header( 'location:adminlogin.php'); } } else { header(
'location:admin_hompage.php'); } ?>
I think there may be a few issues with your script. One obvious one is that you are outputting html content before you send the headers at the bottom of the script.
HTTP headers must be sent to the client before any other content.
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
I would suggest that unless you need to continue processing. You move all your login code to the top of the script and call 'exit()'; after you have sent the headers to the client to prevent any further processing or content being sent to the client.

Omit part of an HTML while using PHP

I'm trying to load part of a targeted URL ($url) into my HTML page, currently the $url page sends back a name, model, type and self recalculate tool - all of which live in a HTML TR tags.
Once I post my daily password from password.php than my users click on $url to get their daily inventory from it, again and i don't mean to be redundant, but the $url itself is provided to me by my clients and I don't want my users to be able to see all the links on that page - Only what pertain to their job.
Also rather than me creating password.php is there a way for me to "collect" this password from my daily outlook exchange email and post it to the header of the $url??
Many thx and I hope i was descriptive enough.
<html>
<head>
<title>Post Password</title>
</head>
<body>
<?php
$password = "";
?>
<form name="password" method="post" action="users.php">
<table border="0" cellspacing="0" cellpadding="2">
<tr>
<td>Paste the Daily Password</td>
<td><input type="text" maxlength=7 name="password"></td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
<html>
<head>
<title>First Page</title>
</head>
<body>
<?php
$url_append = "?secret=";
//$psk = $password;
$linktext = "Click here to get a Pre Shared Key";
$password = $_POST["password"];
$url = "http://example.subexample.xx.com/";
$url .= $url_append;
$url .= $password;
$final_url = $url;
// end base users
?>
<!--I took this form below from the URL that my client host-->
<!--His url have way more input than all_products-->
<!-- but that's the only one that I want to echo for my employees to use -->
<form name="form1" method="post" action="<?php echo htmlspecialchars($final_url);?>">
<table border="0" cellspacing="0" cellpadding="2">
<tr>
<td>Main Inventory</td>
<td><input type="text" maxlength=7 name="all_products"></td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
For sending POST through header take a look at this.
As for the omitting the parts of html, you can use alternative syntax like this
<?php if ($a == 5): ?>
<p>This will be omitted if condition is not true</p>
<?php endif; ?>
Similar can be used for for loop.
Read more on alternative syntax.

Categories