Receiving Error: Notice: Undefined variable – but already defined - php

I dont know what im doing wrong. But i get this
Notice: Undefined variable: num1 in D:\Programs\XAMPP\htdocs\homework\addsub.php on line 15`
<?php
if(isset($_POST['sub']))
{
$num1=$_POST['t1'];
$num2=$_POST['t2'];
if ($_POST['sub']=="+") {
$res= $num1 + $num2;
}
elseif($_POST['sub']=="-"){
$res = $num1-$num2;
}
}
?>
<form action="addsub.php" method="POST">
<input type="text" name="t1" value="<?php echo $num1;?>"><br>
<input type="text" name="t2" value="<?php echo $num2;?>"><br>
<input type="text" name="res" value="<?php echo $res;?>"><br>
<input type="submit" name="sub" value="+">
<input type="submit" name="sub" value="-">
</form>
When I use $num1 or $num2 in textbox values, it shows error. One of my friends used this same code on his laptop but he is using much older version of Xampp. It works fine but later versions of Xampp gives this error. I am using Xampp v3.2.1.

Or initialize the variable if it doesn't exist, like so:
<?php
if (!isset($num1)) {
$num1 = '';
}
Then your HTML could remain unchanged.
The reason I recommend this approach is that it creates clean code - the HTML will always display the value of $num1 and if you choose to initialize it to a different value later, it should be easier to find in the PHP.

use isset to check variable exist or not.
example
<input type="text" name="t1" value="<?php echo isset($num1)?$num1:""; ?>"><br>

You set the $num1 variable only when,
if(isset($_POST['sub']))
So, if the $_POST['sub'] is not there the variable is undefined!

Here is the code, which may help you:
<?php
var $res="";
var $num1="";
var $num2="";
if(isset($_POST['sub']))
{
$num1=$_POST['t1'];
$num2=$_POST['t2'];
if ($_POST['sub']=="+") {
$res= $num1 + $num2;
}
elseif($_POST['sub']=="-"){
$res = $num1-$num2;
}
}
?>
<form action="addsub.php" method="POST">
<input type="text" name="t1" value="<?php echo $num1;?>"><br>
<input type="text" name="t2" value="<?php echo $num2;?>"><br>
<input type="text" name="res" value="<?php echo $res;?>"><br>
<input type="submit" name="sub" value="+">
<input type="submit" name="sub" value="-">
</form>

Related

PHP won't display Echo statement

I'm having trouble checking as to why my echo statement does not appear. I am using a web hosting service so I can use PHP scripts (double checked using simple echo "Hello World!" PHP scripts before). My file does have a .php file extension.
My goal is to simply add two numbers using PHP function from two inputs and just display the result.
<body>
<div>
<form action="index.php">
Enter First Number:<br>
<input type="text" name="first_input" value="">
<br>
Enter Second Number:<br>
<input type="text" name="second_input" value=""><br>
<input type="submit" value="Calculate">
</form>
<?php
function Calc_Addition() {
$first_input = filter_input(INPUT_GET, 'first_input');
$second_input = filter_input(INPUT_GET, 'second_input');
$amount_output = $first_input + $second_input;
echo "$amount_output";
}
?>
</div>
</body>
You need to both parse the input values as numbers (or pass them as such) and execute the function you're calling, like so:
<body>
<div>
<form action="index.php" method="get">
Enter First Number:<br>
<input type="text" name="first_input" value="">
<br>
Enter Second Number:<br>
<input type="text" name="second_input" value=""><br>
<input type="submit" value="Calculate">
</form>
<?php
function Calc_Addition() {
$first_input = intval($_GET['first_input']);
$second_input = intval($_GET['second_input']);
$amount_output = $first_input + $second_input;
echo $amount_output;
}
if(isset($_GET['first_input'])) {
Calc_Addition();
}
?>
</div>
</body>
You need to execute the function. You aren't doing so
<body>
<div>
<form action="index.php">
Enter First Number:<br>
<input type="text" name="first_input" value="">
<br>
Enter Second Number:<br>
<input type="text" name="second_input" value=""><br>
<input type="submit" value="Calculate">
</form>
<?php
//Check if isset, then execute function
if (isset($_GET['first_input'])) {
Calc_Addition();
}
function Calc_Addition() {
$first_input = filter_input(INPUT_GET, 'first_input');
$second_input = filter_input(INPUT_GET, 'second_input');
$amount_output = $first_input + $second_input;
echo "$amount_output";
}
?>
</div>
</body>
I think you need to cast your $first_input and $second_input variables as int's before adding them. So $amount_output would read as follows:
$amount_output = intval($first_input) + intval($second_input);

PHP HTML form session

<?php
session_start();
?>
<html>
<body>
<form action="process.php" method="post">
Name: <input type="text" name="username" value="<?php echo $_SESSION['u']; ?>" />
<input type="submit" value="Submit"/>
</form>
<form action="register.php" method="post">
<input type="submit" value="Register a new user" />
</form>
</body>
</html>
So guys I got this and my question is: I want to use sessions to assign the last registered user as the value of the login form. Everything I got runs ok the thing is if I log in for the first time and I have not started a session i get nothing for the U variable and i get an error message. How can I ... avoid that or something. I tried if statement but in the value section it does not accept {} brackets or something. Any suggestions?
Use isset and assign the session value to a variable instead of using it directly:
if(!isset($_SESSION['u'])){
$u = '';
} else {
$u = $_SESSION['u'];
}
<input type="text" name="username" value="<?php echo $u; ?>" />
An alternative solution - though less cleaner and maintainable - is to utilize PHP's ternary operator:
<input type="text" name="username" value="<?php echo (isset($_SESSION['u']) ? $_SESSION['u'] : ''); ?>" />
Simple explanation of the ternary operator
($statement ? [if $statement == true] : [$statement == false])
using ternary operator..
try this
Name: <input type="text" name="username" value="<?php echo ($_SESSION['u'])?$_SESSION['u']:''; ?>" />
value="<?php echo isset($_SESSION['u'])?$_SESSION['u']:''; ?>"

Update form fields after posting with PHP_SELF

I am using php_self to submit a form. Once the data has been posted, I want to pass a calculated value to another form field on the same page, original form.
The $title_insurance field stays blank. Any ideas on why? Thanks!
<?php
if(isset($_POST['submit']))
{
$sale_price = $_POST['sale_price']; // posted value
$title_insurance = ($sale_price * 0.00575) + 200;
?>
<script type="text/javascript">
document.getElementById("title_insurance").value='<?php echo $title_insurance ; ?>';
</script>
<?php } ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<input name="sale_price" type="text" id="sale_price" size="15">
<input name="title_insurance" type="text" id="title_insurance" size="15" value="<?php echo $title_insurance; ?>" />
<input name="submit" type="submit" class="bordered" id="submit" value="Calculate" />
</form>
The submit button is called button, also if you are outputting a javascript to amend the value it need to be run after the DOM has created the element title_insurance.
if(isset($_POST['button']))
{
$sale_price = $_POST['sale_price']; // posted value
$title_insurance = ($sale_price * 0.00575) + 200;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<input name="sale_price" type="text" id="sale_price" size="15">
<input name="title_insurance" type="text" id="title_insurance" size="15" value="<?php echo $title_insurance; ?>" />
<input name="button" type="submit" class="bordered" id="button" value="Calculate" />
</form>
<script type="text/javascript">
document.getElementById("title_insurance").value='<?php echo $title_insurance ; ?>';
</script>
A better way in this case would be to forget about the javascript as it is unnecessary and do this
// I am assuming you have initialized $title_insurance
// somewhere above here to its default value!!!!
$title_insurance = isset($_POST['button']) ? ($_POST['sale_price'] * 0.00575) + 200 : $title_insurance;
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<input name="sale_price" type="text" id="sale_price" size="15">
<input name="title_insurance" type="text" id="title_insurance" size="15" value="<?php echo $title_insurance; ?>" />
<input name="button" type="submit" class="bordered" id="button" value="Calculate" />
</form>
You have an extra space in your getElementById parameter:
// VV
document.getElementById("title_insurance ").value='<?php echo $title_insurance ; ?>';
What you want to do is best done by AJAX. The <form> construction is outdated and not useful unless you are transferring the user to another page and sending some data along with it - or, if you are finished getting user data and just want to process what was entered and display a completion message.
If you wish to continue processing on the same page, then AJAX is the way to go. And the best way to use AJAX is to have a separate processor file (PHP) that receives the data, processes it, and sends it back.
To convert a <form> construct to AJAX, you really just need to remove the <form></form> tags and convert the submit button from type="submit" to type="button" id="mybutton", and use the IDs on the button and on the other elements to grab the data they contain and feed them to the AJAX code block. The examples in the link at bottom shows what you need to know - they are simple, helpful examples.
To conserve resources, you can use the same PHP processor page for multiple AJAX requests -- just send a variable (eg. 'request=save_to_db&first_name=bob&last_name=jones', ) and test for what "request" is received, that will determine what your PHP processor file does and echoes back.
This post, and the examples it contains, will help.
try this first
In you coding you missed this $_POST['button']
and
<?php
if(isset($_POST['button']))
{
$sale_price = $_POST['sale_price']; // posted value
$title_insurance = ($sale_price * 0.00575) + 200;
?>
<script type="text/javascript">
document.getElementById("title_insurance ").value='<?php echo $title_insurance ; ?>';
</script>
<?php } ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<input name="sale_price" type="text" id="sale_price" size="15">
<input name="title_insurance" type="text" id="title_insurance" size="15" value="<?php echo $title_insurance; ?>" />
<input name="button" type="submit" class="bordered" id="button" value="Calculate" />
</form>
and also refer this FIDDLE it will more helpful to you..

When I use $_POST in php , undefined index happened

I am a PHP programmer, I am confused with the problem below, I am waiting for your guide .
Thanks so much!
There is the html code
<form action="" method="POST">
<div>
<strong>Release: *</strong> <input type="text" name="Release" value="<?php echo $rel; ?>" /><br/>
<strong>User Story ID: *</strong> <input type="text" name="User Story ID" value="<?php echo $id; ?>" /><br/>
<strong>Test Owner *</strong> <input type="text" name="Test Owner" value="<?php echo $owner; ?>" /><br/>
<strong>Date of TC Review *</strong> <input type="text" name="Date of TC Review" value="<?php echo $data; ?>" /><br/>
<strong>By Design </strong> <input type="text" name="By Design" value="<?php echo $design; ?>" /><br/>
<strong>By Review </strong> <input type="text" name="By Review" value="<?php echo $review; ?>" /><br/>
<strong>By Defect </strong> <input type="text" name="By Defect" value="<?php echo $defect; ?>" /><br/>
<p>* required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
There is the php code
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$release = mysql_real_escape_string(htmlspecialchars($_POST['Release']));
// $ID = " abc";
echo $_POST['Release'];
echo $_POST['User Story ID'];
$ID = mysql_real_escape_string(htmlspecialchars($_POST["User Story ID"]));
$T_Owner = mysql_real_escape_string(htmlspecialchars($_POST['Test Owner']));
$data = mysql_real_escape_string(htmlspecialchars($_POST['Date of TC Review']));
$T_ByDesign= mysql_real_escape_string(htmlspecialchars($_POST['By Design']));
$T_ByReview= mysql_real_escape_string(htmlspecialchars($_POST['By Review']));
$T_ByDefect= mysql_real_escape_string(htmlspecialchars($_POST['By Defect']));
// check to make sure both fields are entered
if ($release == '' || $ID == ''||$T_Owner==''||$data=='')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($release, $ID, $T_Owner, $data, $T_ByDesign, $T_ByReview, $T_ByDefect, $error);
}
else
{
// save the data to the database
mysql_query("INSERT Tests SET T_Release='$release', ID='$ID',TestOwner='$T_Owner',T_Date='$data',Test_ByDesign='$T_ByDesign',Test_ByReview='$T_ByReview',Test_ByDefect='$T_ByDefect'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
}
And the error information is below:
Notice: Undefined index: User Story ID in C:\xampp\htdocs\Test\new.php on line 47
abc
Notice: Undefined index: User Story ID in C:\xampp\htdocs\Test\new.php on line 55
Notice: Undefined index: User Story ID in C:\xampp\htdocs\Test\new.php on line 56
Notice: Undefined index: Test Owner in C:\xampp\htdocs\Test\new.php on line 57
Notice: Undefined index: Date of TC Review in C:\xampp\htdocs\Test\new.php on line 58
Notice: Undefined index: By Design in C:\xampp\htdocs\Test\new.php on line 59
Notice: Undefined index: By Review in C:\xampp\htdocs\Test\new.php on line 60
Notice: Undefined index: By Defect in C:\xampp\htdocs\Test\new.php on line 61
You are using invalid name for form input element.
Don't include space in form name.
1st edit your form:
<form action="" method="POST">
<div>
<strong>Release: *</strong> <input type="text" name="Release" value="<?php echo $rel; ?>" /><br/>
<strong>User Story ID: *</strong> <input type="text" name="User_Story_ID" value="<?php echo $id; ?>" /><br/>
<strong>Test Owner *</strong> <input type="text" name="Test_Owner" value="<?php echo $owner; ?>" /><br/>
<strong>Date of TC Review *</strong> <input type="text" name="Date_of_TC_Review" value="<?php echo $data; ?>" /><br/>
<strong>By Design </strong> <input type="text" name="By_Design" value="<?php echo $design; ?>" /><br/>
<strong>By Review </strong> <input type="text" name="By_Review" value="<?php echo $review; ?>" /><br/>
<strong>By Defect </strong> <input type="text" name="By_Defect" value="<?php echo $defect; ?>" /><br/>
<p>* required</p>
<input type="submit" name="submit" value="Submit">
</div>
don't use spaces on the form names, then you can get the post values like this:
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$release = mysql_real_escape_string(htmlspecialchars($_POST['Release']));
echo Print_r($_POST['Release']);
echo Print_r($_POST['User_Story_ID']);
$ID = $_POST["User_Story_ID"];
$T_Owner = $_POST['Test_Owner'];
$data = $_POST['Date_of_TC_Review'];
$T_ByDesign= $_POST['By_Design'];
$T_ByReview= $_POST['By_Review'];
$T_ByDefect= $_POST['By_Defect'];
// check to make sure both fields are entered
if ($release == '' || $ID == ''||$T_Owner==''||$data=='')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($release, $ID, $T_Owner, $data, $T_ByDesign, $T_ByReview, $T_ByDefect, $error);
}
else
{
// save the data to the database
mysql_query("INSERT Tests SET T_Release='$release', ID='$ID',TestOwner='$T_Owner',T_Date='$data',Test_ByDesign='$T_ByDesign',Test_ByReview='$T_ByReview',Test_ByDefect='$T_ByDefect'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
First of all never use "By Design" kinds of coding in php or in any other programming instead of it you should use like this "By_Design" or use cameCaps(byDesign). What is $rel,$id and other stuffs in your html form, you didnot mentioned it. The main problem that is causing in your problem is the use of spaces in your forms and in php.Please don't use it.
I tried some test code:
<form action="" method="POST">
<input type="submit" name="what happened" value="here" />
</form>
<?php
print_r($_POST);
?>
And it seems PHP replaces all elements with spaces in their names to underscores. Thus you'd want to use $_POST['User_Story_ID'] instead of $_POST['User Story ID']. Etc.
You should be define you variable before use. Please check one more time.
Add form action "your_page.php"
Example : <form action="your_page.php" method="POST">
And remove space for form input element like:
echo $_POST['User Story ID'];
instead of this :
Example :
<strong>User Story ID: *</strong> <input type="text" name="UserStoryID" value="<?php echo $id; ?>" /><br/>
echo $_POST['UserStoryID']; or whatever you want to name it

PHP output in the textfield/text

i have a little problem about PHP
there is two input for num1 and num2
and another input answer,,can the output in the php be putted in the input text answer??
<input type="text" name ="num1">
<input type="text" name ="num2">
<input type="text" name ="answer">
Try something like this:
<?php
if(!empty($_POST['num1'])){
$num1 = $_POST['num1'];
$num2 = $_POST['num2']
$answer = $num1 + $num2;
}
?>
<form action="yourpage.php" method="post">
<input type="text" name ="num1" value="<?=#$num1?>">
<input type="text" name ="num2" value="<?=#$num2?>">
<input type="text" name ="answer" value="<?=#$answer?>">
<br/>
<input type="submit" id="btnSubmit" value="POST ME" />
</form>
Not tested btw...
<?php
//get the values and calc..
$answer = $_GET['num1'] + $_GET['num2'];
//more secure, $answer = floor($_GET['num1']) + ...
?>
<html><body>
<form method="get" action=".">
<input type="text" name ="num1">
<input type="text" name ="num2">
<input type="text" name ="answer" value="<?php echo $answer;?>">
<input type="submit">
</form>
...
The jQuery answer that was suggested by riky has shown up on SO before. Try:
How to update the value in one text box based on the value entered in another text box?
As per the OP's request for an fleshed out version of the jQuery answer, modifying the linked to answer gives something like:
$('#num1').change(function() {
var txtAmtval = $('#num1').val() + $('#num2').val();
$('#answer').val(txtAmtval);
});
$('#num2').change(function() {
var txtAmtval = $('#num1').val() + $('#num2').val();
$('#answer').val(txtAmtval);
});
Is that what you had in mind?
Obviously you'd need to include jQuery too.
Please see code in action here: http://jsfiddle.net/9KEsY/

Categories