I'm trying to make a simple web application that adds scores from a physical game such as Scrabble. Most of the code is a HTML form, asking for one input per form element. It then puts the data generated from the form and initializes the appropriate variables. The one part I can't figure out is how to add the new score to the last score. I tried to add variables, like $lastScore, but that didn't seem to work either. Does anyone have any suggestions?
<?php
//Gets data from HTML form
$addScore1 = $_REQUEST['addScore1'];
$addScore2 = $_REQUEST['addScore2'];
//Generates HTML form
echo "<!DOCTYPE html>
<html>
<head>
<title>Score Add</title>
</head>
<body>
<div id=\"displayNames\">
<p>
$player1
<form method=\"post\" action=\"\">
<label for=\"addScore1\">Enter your score:</label>
<input type=\"text\" name=\"addScore1\" id=\"addScore1\" />
<input type=\"submit\" />
</form>
</p>
<p>
$player2
<form method=\"post\" action=\"\">
<label for=\"addScore2\">Enter your score:</label>
<input type=\"text\" name=\"addScore2\" id=\"addScore2\" />
<input type=\"submit\"/>
</form>
</p>
</div>
</body>
</html>";
?>
On submit, the script is calling itself and loses all the variables. You need to store their current score, e.g. in the session, in a database, or in a hidden field in the form.
With hidden field in your form:
<form method="post" action="">
<label for="addScore1">Enter your score:</label>
<input type="text" name="addScore1" id="addScore1" />
<--! the addition is done in the next line in value-->
<input type="hidden" name="oldScore1" id="oldScore1" value="<?=($oldscore1 + $addScore1)?>" />
<input type="submit" />
</form>
Do the same with your second form --> oldScore2 etc...
At the top of your script, read the oldscore from $_REQUEST
//Gets data from HTML form
$addScore1 = $_REQUEST['addScore1'];
$addScore2 = $_REQUEST['addScore2'];
$oldScore1 = $_REQUEST['oldScore1'];
$oldScore2 = $_REQUEST['oldScore2'];
// as alternative, do the addition here:
$oldScore1 += $addScore1;
$oldScore2 += $addScore2;
Rewriting your code as a whole, try it:
I edited all those <?php=$somevalue?>because they don't seem to work with your PHP-setup, and replaced them with <?php echo $somevalue> ?>... let me know how it works...
<?php
// Get data from HTML form. $_POST is fine, because form method is set to POST.
$addScore1 = $_POST['addScore1'];
$addScore2 = $_POST['addScore2'];
$oldScore1 = $_POST['oldScore1'];
$oldScore2 = $_POST['oldScore2'];
// if these are numeric values, add them up
if (is_numeric($addScore1) && is_numeric($oldScore1)) $oldScore1 += $addScore1;
if (is_numeric($addScore2) && is_numeric($oldScore2)) $oldScore2 += $addScore2;
// Generate HTML form -- in HTML, much to complicated in PHP, unless it is necessary for sth else
?>
<html>
<head>
<title>Score Add</title>
</head>
<body>
<div id="displayNames">
<p><?php echo $player1; ?> current score: <?php echo $oldScore1; ?>
<form method="post" action="">
<label for="addScore1">Enter your score:</label>
<input type="text" name="addScore1" id="addScore1" />
<input type="hidden" name="oldScore1" id="oldScore1" value="<?php echo $oldscore1; ?>" />
<input type="submit" />
</p>
<p><?php echo $player2; ?> current score: <?php echo $oldScore2; ?>
<label for="addScore2">Enter your score:</label>
<input type="text" name="addScore2" id="addScore2" />
<input type="hidden" name="oldScore2" id="oldScore2" value="<?php echo $oldscore2; ?>" />
<input type=\"submit\"/>
</form>
</p>
</div>
</body>
</html>
Related
I just want to ask what are the possible errors in SESSION... Because I've been suffering from my bugs! My codes are right but I don't know why it has happened that when I click the submit button it's supposed to pass the value that i declare but it always declare the last value I declared(it means I can't renew the value! once I declared my value that is permanent which is wrong because every time you click the submit it suppose to give new variable)
home.php
<form method="post" action="1home.php">
<label id="checkinD">
<h3>Day</h3>
<Input id="chiD" name="chiD" type="number" min="<?php echo $_SESSION["day_today"]; ?>" max="<?php echo $_SESSION["day_count"]; ?>" required />
</label>
</form>
$chiD = $_POST['chiD'];
$_SESSION["chiD"] = "$chiD";
1home.php
<form method="post" action="2home.php" onsubmit="return validate()">
<label id="checkinD">
<h3>Day</h3>
<Input id="chiD" name="chiD" type="text" value = " <?php echo $_SESSION["chiD"]; ?>" readonly />
</label>
</form>
BTW There is also a crazy one that occurs on my codes it's working very smoothly without logical errors but every 4 hours my codes will have logical errors without my fault!!! it's like automated bugs appeared every hour.
and sometimes to make it work I need to erase the name of my form then replace it again and typed the word that I erased. What kind of shit is this?
PHP, you need to session_start() before assigning values to your
session variables. The date_today variable holds the present datetime, and date_count variable holds a random number.
Though i can not see your full code but here's the working solution.
home.php
<?php
session_start();
$_SESSION["day_today"] = date("Y-m-d H:i:s");
$_SESSION["day_count"] = rand();
?>
<form method="post" action="1home.php">
<label id="checkinD"><h3>Day</h3></label>
<Input id="chiD" name="chiD" type="number" min="<?php echo $_SESSION["day_today"]; ?>" max="<?php echo $_SESSION["day_count"]; ?>" required />
<input type="submit" value="FORM 2" name="btn_form2" >
</form>
home1.php
<?php
session_start();
if(isset($_POST['chiD'])):
$chiD = $_POST['chiD'];
$_SESSION["chiD"] = $chiD;
?>
<form method="post" action="2home.php" onsubmit="return validate()">
<label id="checkinD"><h3>Day</h3></label>
<input id="chiD" name="chiD" type="text" value = "<?php echo $_SESSION["chiD"]; ?>" readonly />
</form>
<?php echo "Day: ". $_SESSION['day_today']; ?>
<br>
<?php echo "Day Count: ". $_SESSION['day_count']; ?>
<?php else: ?>
<h4> Sorry! Somethinh went wrong. </h4>
<?php endif; ?>
Here's a screenshot of the result
Hope this helps
I have some data in a session and I want to save it in text box value, using PHP. But the problem is when saving, just first token of string will be saved, like below example:
<?php session_start();?>
<html >
<head>
</head>
<body>
<form >
<?php echo $_SESSION['institute']="rebaz salih" ?>
<input type="text" <?php echo "value=".$_SESSION['institute']; ?> required />
</form>
</body>
Output will be:
rebaz salih
rebaz
Couple of things:
<?php echo $_SESSION['institute']="rebaz salih" ?>
Is this supposed to be the assignment? or just a print line? in any case, try getting rid of the echo.
Both #edCoder, and #chethan194 are on the right track... the value belongs on the outside, but you really should be using a new variable for institute. For example:
//htmlspecialchars will clear out any quotes, etc so it will work in the browser.
<?php
$value = htmlspecialchars($_SESSION['institute'], ENT_QUOTES);
?>
<form >
<input type="text" value = "<?php print $value; ?>" required />
</form>
Here is the full example:
<?php
php session_start();
//i don't know where you get the institute, so i will leave it here for now...
$_SESSION['institute']="rebaz salih";
$value = '';
if (!empty($_SESSION['institute']))
{
$value = htmlspecialchars($_SESSION['institute'], ENT_QUOTES);
}
?>
<html>
<head>
</head>
<body>
<form>
<input type="text" value = "<?php print $value; ?>" required />
</form>
</body>
You can put the value attribute outside php
<?php echo $_SESSION['institute']="rebaz salih" ?>
Wrong - <input type="text" <?php echo "value=".$_SESSION['institute']; ?> />
Right - <input type="text" value = "<?php echo $_SESSION['institute'];?>" />
</form>
<input type="text" value="<?php echo $_SESSION['institute']; ?>" required/>
I would like to add an input element to the form dynamically using only PHP.
I know how to make this using php and JavaScript combination, thus do nto advice abotu JavaScript.
The example below does not work. Could you please advice and comment:
input.php
<br> <input type="text" name="mob[]" value="" size="3" >
form.php
<?php
if( isset($_POST['AddNum']) ){
$AddNumCount=$_POST['AddNumCount'];
$AddNumCount=$AddNumCount+1;
echo $AddNumCount;
}
if( isset($_POST['register']) ){
print_r($_POST['register']);
}
if (!isset($AddNumCount)) {$AddNumCount=5;}
?>
<form action="" method="post" id="form1" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >
<br>
<?php for ($i=0; $i<$AddNumCount; $i++) { Include('input.php'); } ?>
<br> Add number: <input type="submit" name="AddNum" form="form1" value="Add NUmber"> </p>
<input type="hidden" name="AddNumCount" form="form1" value=" <?php $AddNumCount; ?> "> </p>
<br></form><input type="submit" name="register" id="regcont" value="register"> </p>
</form>
Maybe you know how to make single submit button for many forms?
I mean each input would be a separare form and all forms can be submittted with the button on the end?
You use two action attrs. Maybe you mean:
<form method="post" id="form1" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >
For submitting many forms by one button - you need to use JavaScript and send them in cycle via AJAX.
I am sorry i change this post. This is working example for dynamical PHP.
Use EXform.php. Other files are generated or helping.
Maybe it is also possible to make this using Session variables and header for redirecting to regenerated webpage.
EXform.php
<?php if (isset( $_POST['AddNum'])) { Include("GENinput.php"); } ?>
<?php if (!isset( $_POST['AddNumCount'])) { $_POST['AddNumCount']=1; Include("GENinput.php"); } ?>
<form action="" method="post" id="form1" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >
<?php Include("INCinput.php"); ?>
<br> Add number: <input type="submit" name="AddNum" form="form1" value="Add NUmber"> </p>
<input type="hidden" name="AddNumCount" form="form1" value="<?php echo $AddNumCount; ?>"> </p>
<input type="submit" name="register" id="regcont" value="register"> </p>
<br></form>
</form>
GENinput.php // generates included file
<?php
if( isset($_POST['AddNum']) ){
$AddNumCount=$_POST['AddNumCount']; //=
$fnameinp="INCinput.php";
$fileinp=fopen($fnameinp,"w");
$_POST['AddNumCount']=$AddNumCount=$AddNumCount+1;
//echo "AddNumCount=".$AddNumCount;
$strV=""; $stri="";
for ($i=0; $i<$AddNumCount; $i++) {
$strV.=" \n
<?php
if( isset(\$_POST['v']['tname']['colname'][".$i."]) )
{ \$v['tname']['colname'][".$i."]=\$_POST['v']['tname']['colname'][".$i."];}
else { \$v['tname']['colname'][".$i."]=".$i."; }
?>
";
$stri.=" <br> <input type=\"text\" name=\"v[tname][colname][".$i."]\" value=\"<?php echo \$v['tname']['colname'][".$i."]; ?>\" > \n\n";
}
fwrite($fileinp,$strV);
fwrite($fileinp,$stri);
fclose($fileinp);
}
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..
I have two pages, A and B.
I want to echo a variable written in A inside of the page in B.
Here's the first page:
<?php session_start(); ?>
<html>
<head>
<title>Registration Form - 1 of 2</title>
</head>
<body>
<h1>Registration - Part 1 of 2</h1>
<p>Please fill in all the required information before submitting the information.</p>
<form action="registerFormTwo.php" method="post">
First Name:<input type="text" name="firstName" /><br /><?php $_SESSION['firstName'] = firstName; ?>
Last Name:<input type="text" name="lastName" /><br /><?php $_SESSION['lastName'] = lastName; ?>
Age:<input type="text" name="age" /><br /><?php $_SESSION['age'] = age; ?>
Date of Birth:<input type="text" name="dateOfBirth" /><br /><?php $_SESSION['dateOfBirth'] = dateOfBirth; ?>
<input type="submit" />
</form>
</body>
And here's the second one:
<?php session_start(); ?>
<html>
<head>
<title>Registration Form - 2 of 2</title>
</head>
<body>
<h1>Registration - Part 2 of 2</h1>
<p>Please fill in all the required information before submitting the information.</p>
<?php //wrote this in just to test that session information is saving, but it isn't.
echo $_SESSION['name']; ?>
<form action="registerFinish.php" method="post">
Nationality<input type="text" name="nationality" /><br /><?php $_SESSION['nationality'] = nationality; ?>
Profession:<input type="text" name="profession" /><br /><?php $_SESSION['profession'] = profession; ?>
<input type="submit" />
</form>
</body>
On the second page, the name variable should be echoed, but nothing shows.
Thank you for the help.
EDIT:
Here's the code on formOne and it's still not working:
<?php session_start();
if ($_POST) {
// Store our name in the session array
$_SESSION["firstName"] = $_POST["firstName"];
}
?>
<html>
<head>
<title>Registration Form - 1 of 2</title>
</head>
<body>
<h1>Registration - Part 1 of 2</h1>
<p>Please fill in all the required information before submitting the information.</p>
<form action="registerFormTwo.php" method="post">
First Name:<input type="text" name="firstName" /><br />
Last Name:<input type="text" name="lastName" /><br /><?php $_SESSION['lastName'] = lastName; ?>
Age:<input type="text" name="age" /><br /><?php $_SESSION['age'] = age; ?>
Date of Birth:<input type="text" name="dateOfBirth" /><br /><?php $_SESSION['dateOfBirth'] = dateOfBirth; ?>
<input type="submit" />
</form>
</body>
</html>
Form data doesn't go directly into $_SESSION. You have to place it there. Since your form method is POST, you could pull your data out of $_POST on the server-side:
session_start();
if ($_POST) {
// Store our name in the session array
$_SESSION["name"] = $_POST["name"];
}
If you simply want to keep values in a form when the form submission failed, you don't need to use sessions. You can reprint the value from $_POST directly into the markup again:
<input type="text" name="name" value="<?php print $_POST["name"]; ?>" />
Keep in mind that all of this takes place on the page that you're posting to. If your first form is on page1.php, then you would ignore all of this. If you're posting from page1.php to page2.php, you would place the aforementioned code on page2.php.
Update
I just noticed the following beside your form elements:
<?php $_SESSION['lastName'] = lastName; ?>
lastName doesn't represent anything here. $_POST["lastName"] would represent the posted data. If you were trying to print the last-submitted value, I would do this:
<?php print $_POST["lastName"]; ?>