I have three text boxes and I want to place a value in textbox 1 and 2,then add them together and get the result in textbox 3.With the below code I can get it to echo out onto the screen,but If I omit the echo then nothing happens after placing numbers in T1 andT2.
Can anybody tell me what I am doing wrong.
<html>
<head>
<title>My Page</title>
</head>
<body>
<br>
<form name="myform" action="textentry2.php" method="POST">
<input type = "submit" name = "submit" value = "go">
<input type = "text" name = "text1" >
<input type = "text" name = "text2" >
<input type = "text" name = "text3" >
<?php
$text_entry = $_POST['text1'];
$text_entry2 = $_POST['text2'];
$text_entry3 = $_POST['text3'];
{
$text_entry3 = ($text_entry + $text_entry2);
echo ($text_entry3);
}
?>
nothing happens after placing numbers in T1 andT2
PHP is a server-side language. you can't expect from PHP to act real-time...
input values need to go to server, then PHP Server can calculate your values on server then after refresh, results comes...
if you want to write a real-time calculator, you need to write this with javaScript. absolutely you can do that with AJAX or anything else but javaScript is a easy and fast way for this.
try this:
<html>
<head>
<title>My Page</title>
</head>
<body>
<br>
<form name="myform" action="textentry2.php" method="POST">
<input type="submit" name="submit" value = "go">
<input type="text" name="text1" onkeyup="calc()">
<input type="text" name="text2" onkeyup="calc()">
<input type="text" name="text3" >
</form>
<script>
function calc()
{
var elm = document.forms["myform"];
if (elm["text1"].value != "" && elm["text2"].value != "")
{elm["text3"].value = parseInt(elm["text1"].value) + parseInt(elm["text2"].value);}
}
</script>
</body>
</html>
For Strings:
$text_entry3 = ($text_entry.$text_entry2);
in php you combine strings with a . between them.
For Integer:
$text_entry3 = ((int)$text_entry + (int)$text_entry2);
You need to cast them as you get Strings from your from and they won't add together that easy without casting.
For Placing it:
as Aravona stated allready:
You should make all the calculation befor you output the html. Php is dynamic. HTML not. Thus you need to put the dynamic part into the static one
Make the <?php ... ?> in the beginnin and than use this to output the result:
<input type = "text" name = "text3" value="<?=$text_entry3;?>" >
I think your code would be like this:
<?php
$text_entry1 = (int)$_POST['text1'];
$text_entry2 = (int)$_POST['text2'];
$text_entry3 = ($text_entry1 + $text_entry2);
?>
<html>
<head>
<title>My Page</title>
</head>
<body>
<br>
<form name="myform" action="textentry2.php" method="POST">
<input type = "submit" name = "submit" value = "go">
<input type = "text" name = "text1" value = "<?php echo $text_entry1 ?>" >
<input type = "text" name = "text2" value = "<?php echo $text_entry2 ?>" >
<input type = "text" name = "text3" value = "<?php echo $text_entry3 ?>" >
</form>
</body>
</html>
Firstly put your PHP above your HTML so the values are defined.
Then:
<input type = "text" name = "text3"
value="<?php echo ((int)$text_entry + (int)$text_entry2); ?>">
A very good tips I tend to give those who are new to PHP, is to put all of your PHP code before any HTML. This means that you'll take care of all of your data processing, before you try to send the client anything. The beauty of that, is that if some erroneous condition appears, you can simply redirect or do whatever's necessary to provide the user with a clear and informative responce. Instead of just dumping a half-created page, with an ugly error (or several) in the middle of it.
Thus your PHP code should look something like this:
<?php
// First make sure that the variable is defined, to prevent notices
// when trying to use it later.
$answer = '';
// If something has been posted (submitted).
if (!empty ($_POST)) {
// Calculate the answer.
// TODO: Add some validation to make sure that the values are indeed numbers.
// See filter_var () in the PHP manual.
$answer = $_POST['text1'] + $_POST['text2'];
}
?>
<html>
<head>
<title>My Page</title>
</head>
<body>
<form name="myform" action="textentry2.php" method="POST">
<input type="submit" name="submit" value = "go">
<input type="number" name="text1" >
<input type="number" name="text2" >
<input type="number" name="text3" value="<?php echo $answer; ?>">
</form>
Normally I'd use htmlspecialchars() on $answer when echoing it, to prevent XSS attacks. However, since it only echo out a number it is not necessary in this case.
Related
I am new to PHP and have just started learning it. I may have gotten in over my head. I am trying to have a user input a buy value and a sell value in an html form, and then have php perform mathematical operations on those values, and finally, output the value calculated by the math operations.
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<form action="" method="post">
Buy Price: <input type="number" name="buyprice" value="<?php echo
$buyprice;?>">
Sell Price: <input type="number" name="sellprice" value="<?php echo
$sellprice;?>">
<input type="submit" name="submit" value="Calculate" />
</form>
<?PHP
$buyprice = $_POST['buyprice'];
$sellprice = $_POST['sellprice'];
$tax = 0.95;
$profit = 0;
if (isset($_POST['submit'])) { //to check if the form was submitted
$profit = (($sellprice * $tax) - $buyprice);
print $profit;
}
?>
</body>
</html>
This is my attempt at it, I would appreciate any tips or ideas on how to accomplish what I want to do. Basically, the user inputs two values into the form, the php needs to use those values as variables and perform mathematical operations with them, and then I need it to output the calculated value to the page. The calculation should not be performed until the user presses the calculate button.
I'm also curious if there is a way to prevent the user from adding numbers that are negative in value (min max?). I was also wondering if there was a way to remove the arrows from the input boxes in the form.
Thanks.
Your code works, you just messed up on where to put your PHP.
<?PHP
$buyprice = $_POST['buyprice'];
$sellprice = $_POST['sellprice'];
$tax = 0.95;
$profit = 0;
if (isset($_POST['submit'])) { //to check if the form was submitted
$profit = (($sellprice * $tax) - $buyprice);
print $profit;
}
?>
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<form action="" method="post">
Buy Price: <input type="number" name="buyprice" value="<?php echo
$buyprice;?>">
Sell Price: <input type="number" name="sellprice" value="<?php echo
$sellprice;?>">
<input type="submit" name="submit" value="Calculate" />
</form>
</body>
</html>
To remove the arrows on the right, you can swap out <input type="number" for <input type="textbox".
To stop users from inputting negative numbers, you can use the pattern element for this.
<input type="textbox" pattern="^[1-9][0-9]*$"
^[1-9][0-9]*$ is regex for any number above 0, however it won't accept a decimal.
If you can live with the arrows, then you can set a min property to stop input going below 0.
<input type="number" min="0"
NOTE: Even tho you are stopping users from inputting a value > 0. A malicious user may still send a fake $_POST value to your page. If you're doing anything sensitive with $_POST/$_GET/$_REQUEST you cannot trust it.
I have been working with some code that will check the name servers of a domain. If the name servers contain the word "inmotion", I want the label in my HTML form to say "Nameservers have been updated", else it should say "Name servers have not been updated".
The only thing I am confused about is making the label in the form say whether they have been updated.
Here is the working PHP code:
<?php
$b = $_REQUEST['domain'];
$dns = dns_get_record($b, DNS_NS);
$c = $dns[0]['target'];
$d = $dns[1]['target'];
if (strpos($c, 'inmotion') !== false) {
echo 'Nameservers have been updated';
}else {
echo "Nameservers haven't been updated";
}
?>
Here is my HTML code:
iframe{
display:none;
}
<form action="dnscheck.php" target="my_iframe" class = "input" method="post">
<label class = "label" for="other">Verify Domain Connection</label><br />
<input class = "field" type="text" name="domain" /><br />
<input type="submit" class = "btn" name="submit" value="Verify" />
<iframe class="iframe" name="my_iframe" src="not_submitted_yet.aspx"></iframe>
<label name="result" id="result></label>
</form>
If your iframe isn't cross domain, you could write javascript in your child iframe to set the value of the label in the paren't document.
Something like this
<?php
$var = "Hello World";
?>
<script>
parent.document.getElementById("myLabel").value = "<? echo $var; ?>";
</script>
If they are cross domain, your best bet would be to use the iframe as the label. Remove the label, echo the value you want to show in the label and style your iframe accordingly.
I'm just getting into mysql and i am creating a basic registration page. However, when i click submit, i want to be directed to another page, say a page where you login, as many sites have.
How do i go about allowing the submit button to link to a new page. I know it'll be something simple, but i have looked and can't seem to find much on it.
This is the current code that i've tried:
<html>
<head>
<title>MySQL Test - Registration</title>
<script LANGUAGE="JavaScript">
function testResults() {
window.document.location.href = "http://www.google.com";
}
</script>
</head>
<body>
<form action = "rego.php" method = "POST">
Username:<br/>
<input type = "text" name = "username"/><br/>
Password:<br/>
<input type = "password" name = "password"/><br/>
Confirm Password:<br/>
<input type = "password" name = "passvery"/><br/>
Email:<br/>
<input type = "text" name = "email"/><br/><br/>
Please select your gender:<br/>
<input type = "radio" name = "gender" value = "male"/>Male      
<input type = "radio" name = "gender" value = "female"/>Female<br/><br/>
<input type = "checkbox" name = "agree" value = "agree"/>I agree to the terms and conditions.<br/>
<br/>
<input type = "submit" value = "Sign Up!" onclick = "javascript:testresults()" />
</form>
</body>
</html>
Form action="rego.php" means that your form will be submitted to that file.
If you want to go somewhere else after rego.php, you should redirect from that file, for example using the location header, before any output:
// do stuff (registration)
header("Location: another-php.php");
I have a input field as follows:
<input type="text" name="subject" id="subject" value="Car Loan">
I would like to get the input fields value Car Loan and assign it to a session. How do I do this using PHP or jQuery?
Use PHP's $_POST or $_GET superglobals to retrieve the value of the input tag via the name of the HTML tag.
For Example, change the method in your form and then echo out the value by the name of the input:
Using $_GET method:
<form name="form" action="" method="get">
<input type="text" name="subject" id="subject" value="Car Loan">
</form>
To show the value:
<?php echo $_GET['subject']; ?>
Using $_POST method:
<form name="form" action="" method="post">
<input type="text" name="subject" id="subject" value="Car Loan">
</form>
To show the value:
<?php echo $_POST['subject']; ?>
Example of using PHP to get a value from a form:
Put this in foobar.php:
<html>
<body>
<form action="foobar_submit.php" method="post">
<input name="my_html_input_tag" value="PILLS HERE"/>
<input type="submit" name="my_form_submit_button"
value="Click here for penguins"/>
</form>
</body>
</html>
Read the above code so you understand what it is doing:
"foobar.php is an HTML document containing an HTML form. When the user presses the submit button inside the form, the form's action property is run: foobar_submit.php. The form will be submitted as a POST request. Inside the form is an input tag with the name "my_html_input_tag". It's default value is "PILLS HERE". That causes a text box to appear with text: 'PILLS HERE' on the browser. To the right is a submit button, when you click it, the browser url changes to foobar_submit.php and the below code is run.
Put this code in foobar_submit.php in the same directory as foobar.php:
<?php
echo $_POST['my_html_input_tag'];
echo "<br><br>";
print_r($_POST);
?>
Read the above code so you know what its doing:
The HTML form from above populated the $_POST superglobal with key/value pairs representing the html elements inside the form. The echo prints out the value by key: 'my_html_input_tag'. If the key is found, which it is, its value is returned: "PILLS HERE".
Then print_r prints out all the keys and values from $_POST so you can peek as to what else is in there.
The value of the input tag with name=my_html_input_tag was put into the $_POST and you retrieved it inside another PHP file.
You can get the value $value as :
$value = $_POST['subject'];
or:
$value = $_GET['subject']; ,depending upon the form method used.
session_start();
$_SESSION['subject'] = $value;
the value is assigned to session variable subject.
For global use, you may use:
$val = $_REQUEST['subject'];
and to add yo your session, simply
session_start();
$_SESSION['subject'] = $val;
And you dont need jQuery in this case.
function get_input_tags($html)
{
$post_data = array();
// a new dom object
$dom = new DomDocument;
//load the html into the object
$dom->loadHTML($html);
//discard white space
$dom->preserveWhiteSpace = false;
//all input tags as a list
$input_tags = $dom->getElementsByTagName('input');
//get all rows from the table
for ($i = 0; $i < $input_tags->length; $i++)
{
if( is_object($input_tags->item($i)) )
{
$name = $value = '';
$name_o = $input_tags->item($i)->attributes->getNamedItem('name');
if(is_object($name_o))
{
$name = $name_o->value;
$value_o = $input_tags->item($i)->attributes->getNamedItem('value');
if(is_object($value_o))
{
$value = $input_tags->item($i)->attributes->getNamedItem('value')->value;
}
$post_data[$name] = $value;
}
}
}
return $post_data;
}
error_reporting(~E_WARNING);
$html = file_get_contents("https://accounts.google.com/ServiceLoginAuth");
print_r(get_input_tags($html));
If its a get request use, $_GET['subject'] or if its a post request use, $_POST['subject']
<form action="" method="post">
<input type="text" name="subject" id="subject" value="Car Loan">
<button type="submit" name="ok">OK</button>
</form>
<?php
if(isset($_POST['ok'])){
echo $_POST['subject'];
}
?>
I am trying to add commenting like StackOverflow and Facebook uses to a site I'm building. Basically, each parent post will have its own child comments. I plan to implement the front-end with jQuery Ajax but I'm struggling with how to best tackle the PHP back-end.
Since having the same name and ID for each form field would cause validation errors (and then some, probably), I added the parent post's ID to each form field. Fields that will be passed are commentID, commentBody, commentAuthor - with the ID added they will be commentTitle-12, etc.
Since the $_POST array_key will be different each time a new post is processed, I need to trim off the -12 (or whatever the ID may be) from the $_POST key, leaving just commentTitle, commentBody, etc. and its associated value.
Example
$_POST['commentTitle-12']; //how it would be received after submission
$_POST['commentTitle']; //this is what I am aiming for
Many thanks
SOLUTION
Thanks to CFreak-
//Basic example, not actual script
<?php
if (array_key_exists("send", $_POST)) {
$title = $_POST['title'][0];
$body = $_POST['body'][0];
echo $title . ', ' . $body;
}
?>
<html>
<body>
<form name="test" id="test" method="post" action="">
<input type="text" name="title[]"/>
<input type="text" name="body[]"/>
<input type="submit" name="send" id="send"/>
</form>
</body>
</html>
Update 2
Oops, kind of forgot the whole point of it - unique names (although it's been established that 1) this isn't really necessary and 2) probably better, for this application, to do this using jQuery instead)
//Basic example, not actual script
<?php
if (array_key_exists("send", $_POST)) {
$id = $_POST['id'];
$title = $_POST['title'][$id];
$body = $_POST['body'][$id];
echo $title . ', ' . $body;
}
?>
<html>
<body>
<form name="test" id="test" method="post" action="">
<input type="text" name="title[<?php echo $row['id'];?>]"/>
<input type="text" name="body[<?php echo $row['id'];?>]"/>
<input type="hidden" name="id" value="<?php echo $row['id']; //the ID?>"/>
<input type="submit" name="send" id="send"/>
</form>
</body>
</html>
PHP has a little trick to get arrays or even multi-dimensional arrays out of an HTML form. In the HTML name your field like this:
<input type="text" name="commentTitle[12]" value="(whatever default value)" />
(you can use variables or whatever to put in the "12" if that's what you're doing, the key is the [ ] brackets.
Then in PHP you'll get:
$_POST['commentTitle'][12]
You could then just loop through the comments and grabbing each by the index ID.
You can also just leave it as empty square brackets in the HTML:
<input type="text" name="commentTitle[]" value="(whatever default value)" />
That will just make it an indexed array starting at 0, if you don't care what the actual ID value is.
Hope that helps.
You just have to iterate through $_POST and search for matching keys:
function extract_vars_from_post($arr) {
$result = array();
foreach ($arr as $key => $val) {
// $key looks like asdasd-12
if (preg_match('/([a-z]+)-\d+/', $key, $match)) {
$result[$match[1]] = $val;
} else {
$result[$key] = $val;
}
}
return $result;
}
Didn't test the code, though