Adding values to Text Area - php

I'm trying to add 'guess' so that it shows in the text area without deleting the previous input. So that if you guessed '12' then '15' then '20'.
It would display in the text area as
12
15
20.
Rather than just displaying the most current value that you had entered for guess.
I've tried to put it into an array inside of the session, but the submit button is messing up the array when I try to display it inside of the textarea.
Any help would be greatly appreciated, thank you.
<?php
session_start();
if (!isset($_POST["guess"])) {
$_SESSION["AmountofGuesses"] = 0;
$message = "Guessing Game";
$_POST["Answer"] = rand(0,1000);
}
else if ($_POST["guess"] > $_POST["Answer"]) {
$message = $_POST["guess"]." is too high, try guessing lower.";
$_SESSION["AmountofGuesses"]++;
}
else if ($_POST["guess"] < $_POST["Answer"]) {
$message = $_POST["guess"]." is too low, try guessing higher.";
$_SESSION["AmountofGuesses"]++;
}
else {
$_SESSION["AmountofGuesses"]++;
$message = "You've guessed the correct number in,
".$_SESSION["AmountofGuesses"]." guess/guesses! Click restart to start a new
game.";
unset($_SESSION["AmountofGuesses"]);
}
if (isset($_POST["guess"])) {
$button= $_POST["button"];
$ArrayofNumbers = array();
array_push($ArrayofNumbers,$_POST["guess"]);
if ($button=="Restart"){
$message = "Guessing Game";
$_POST["Answer"] = rand(0,1000);
$_SESSION["AmountofGuesses"] = 0;
}
if ($button=="Answer"){
$message = "You've given up, your answer is above. Click restart to start a
new game.";
$_SESSION["AmountofGuesses"] = 0;
echo $_POST["Answer"];
}
}
?>
<title>Guessing Game</title>
<h3><?php echo $message; echo $ArrayofNumbers;?></h3>
<form action "program1.php" method="POST">
<table border="2" cellspacing="6">
<td>
<br/>
<p>Guess: <input type="text" name="guess"/> </p>
<input type="hidden" name="Answer" value="<?php echo $_POST["Answer"]; ?>" >
<p>Number of guesses: <?php echo $_SESSION["AmountofGuesses"]; ?> </p>
<center><input type="submit" name="button" value="Submit"></center>
<br/>
<center><input type="submit" name="button" value="Restart"></center>
<br/>
<center><input type="submit" name="button" value="Answer"></center>
</td>
<td>
<textarea name="paragraph_text" cols="50" rows="10">
<?php if (isset($ArrayofNumbers)) {echo implode("\n", $ArrayofNumbers);}?>
</textarea>
</td>
</table>
</br>
Back to Home

You can add another New Session by using the command condition for your array as below:
<?php session_start();
if (!isset($_POST["guess"])) {
$_SESSION["AmountofGuesses"] = 0;
$message = "Guessing Game";
$_POST["Answer"] = rand(0,1000);
}else if ($_POST["guess"] > $_POST["Answer"]) {
$message = $_POST["guess"]." is too high, try guessing lower.";
$_SESSION["AmountofGuesses"]++;
}else if ($_POST["guess"] < $_POST["Answer"]) {
$message = $_POST["guess"]." is too low, try guessing higher.";
$_SESSION["AmountofGuesses"]++;
}else {
$_SESSION["AmountofGuesses"]++;
$message = "You've guessed the correct number in,
".$_SESSION["AmountofGuesses"]." guess/guesses! Click restart to start a new
game.";
unset($_SESSION["AmountofGuesses"]);
}
if (isset($_POST["guess"])) {
$button= $_POST["button"];
if(#$_SESSION["guess"]!=''){
array_push($_SESSION["guess"],$_POST["guess"]);
}else{
$ArrayofNumbers = array();
array_push($ArrayofNumbers,$_POST["guess"]);
$_SESSION["guess"]=$ArrayofNumbers;
}
if ($button=="Restart"){
$message = "Guessing Game";
$_POST["Answer"] = rand(0,1000);
$_SESSION["AmountofGuesses"] = 0;
unset($_SESSION["guess"]);
}
if ($button=="Answer"){
$message = "You've given up, your answer is above. Click restart to start a
new game.";
$_SESSION["AmountofGuesses"] = 0;
unset($_SESSION["guess"]);
echo $_POST["Answer"];
}
}
?>
<title>Guessing Game</title>
<h3><?=$message?></h3>
<form action "" method="POST">
<table border="2" cellspacing="6">
<td>
<br/>
<p>Guess: <input type="text" name="guess"/> </p>
<input type="hidden" name="Answer" value="<?=#$_POST["Answer"]?>" >
<p>Number of guesses: <?=#$_SESSION["AmountofGuesses"]?> </p>
<center><input type="submit" name="button" value="Submit"></center>
<br/>
<center><input type="submit" name="button" value="Restart"></center>
<br/>
<center><input type="submit" name="button" value="Answer"></center>
</td>
<td>
<textarea name="paragraph_text" cols="50" rows="10">
<?php if (#$_SESSION["guess"]!='') {
foreach ($_SESSION["guess"] as $value) {
echo $value."\n";
}
}?>
</textarea>
</td>
</table>
</form>

If you are ok with the output being similar to 12 15 20, then you can change $ArrayofNumbers to perhaps $PastGuesses and then append each next answer as a regular string.
$PastGuesses .= " " . $_POST["guess"];
And make sure $PastGuesses is still stored in $_SESSION.

Related

call variable using $_POST php

<body onload="cmdform.command.focus()">
<form method="POST" action="#" name="cmdform">
<textarea style="width:100%; height:90%; background:black; color:green;" name="textarea" cols="20" >
<?php
$name="My Name";
if (isset($_POST['submit'])){
if (!empty($_POST['command'])){
echo $me = $_POST['textarea'];
echo "\n";
echo $_POST['command'];
}else{
echo $me = $_POST['textarea'];
}
}
?>
</textarea>
<input type="text" name="command">
<input type="submit" value="Submit" name="submit">
<input type="reset" value="Reset" name="B2">
</form></body>
When I enter $name in textbox("command")
'My Name' should display in textarea
You can solve this with a simple str_replace() call.
$content = str_replace('$name', $name, $content);
Or you use an if() statement to check if the content is exactly the string "$name".
if ($_POST['command'] == '$name') {
$content = $name;
}

I have multiple submit buttons and a validation issue with the second form

So I have two forms that are hidden when submitted. The validation for the second form isn't working. Any clue as to why?
if(isset($_POST['submit'])){
$feet = $_POST['feet'];
$lname = $_POST['lname'];
if(!is_numeric($feet)){
$isValid = false;
$feetError = "Try again buddy";
}
echo "Hello Captain " . $lname . " Are you" . $feet ."ft tall?";
}
elseif(isset($_POST['submit2'])){
$feet2 = $_POST['feet2'];
$lname2 = $_POST['lname2'];
$isValid2 = true;
if(!is_numeric($feet2)){
$isValid2 = false;
$feetError2 = "Try again buddy";
}
echo "Hello Captain " . $lname2 . " Are you" . $feet2 ."ft tall?";
}
else{
?>
<form name="formie" id="formie" action="test1.php" method="post">
<p><label>square feet</label><input type="text" id="feet" name="feet"><span><?PHP echo $feetError; ?></span></p>
<p><label>Last Name</label><input type="text" id="lname" name="lname"></p>
<p><button type="submit" name="submit" id="submit">Submit</button></p>
</form>
<form name="formie2" id="formie2" action="test1.php" method="post">
<p><label>square feet</label><input type="text" id="feet2" name="feet2"><span><?PHP echo $feetError2; ?></span></p>
<p><label>Last Name</label><input type="text" id="lname2" name="lname2"></p>
<p><button type="submit" name="submit2" id="submit2">Submit</button></p>
</form>
<?PHP
}
?>
These are all place holders BTW. The project I'm working on is much much larger, I just want to understand the whole 'hiding forms' thing before I try to implement it on a larger scale.
Thank You guys!
$isSubmitted = false;
$isValid = true;
$isValid2 = true;
$feetError = '';
$feetError2 = '';
if(isset($_POST['submit'])){
$isSubmitted = true;
$feet = $_POST['feet'];
$lname = $_POST['lname'];
if(!is_numeric($feet)){
$isValid = false;
$feetError = "Try again buddy";
} else {
echo "Hello Captain " . $lname . " Are you" . $feet ."ft tall?";
}
}
elseif(isset($_POST['submit2'])){
$isSubmitted = true;
$feet2 = $_POST['feet2'];
$lname2 = $_POST['lname2'];
if(!is_numeric($feet2)){
$isValid2 = false;
$feetError2 = "Try again buddy";
} else {
echo "Hello Captain " . $lname2 . " Are you" . $feet2 ."ft tall?";
}
}
?>
<?php if(!$isSubmitted || !$isValid || !$isValid2) { ?>
<form name="formie" id="formie" action="test1.php" method="post">
<p><label>square feet</label><input type="text" id="feet" name="feet"><span><?PHP echo $feetError; ?></span></p>
<p><label>Last Name</label><input type="text" id="lname" name="lname"></p>
<p><button type="submit" name="submit" id="submit">Submit</button></p>
</form>
<form name="formie2" id="formie2" action="test1.php" method="post">
<p><label>square feet</label><input type="text" id="feet2" name="feet2"><span><?PHP echo $feetError2; ?></span></p>
<p><label>Last Name</label><input type="text" id="lname2" name="lname2"></p>
<p><button type="submit" name="submit2" id="submit2">Submit</button></p>
</form>
<?php } ?>
When you submit a form, the PHP reloads the page. When the page is reloaded, it is reloaded WITH the previous posted values of your form. Therefore it will always trigger your first condition assuming the user is submitting the first form first.
You have 2 solutions. Do separate script, or use another if, instead the if - else. I'd recommend separate script though.
I recommend separate script for each form, with a header redirecting to your website after, it's easier to remember and to order your work afterwards.

Why Can't I Pass a String?

I'm trying to get a quiz program to work in PHP. Up until now, I've had little problem getting any code I write to work. However, this time, I can't seem to get a string to pass to the next page of a form. The basic idea is a trivia program. A random question is retrieved, the user answers the question, the program checks to see if the answer is right. Eventually, the program will keep score, but I haven't got that far yet because I can't seem to check the answer against the question. I can't figure out where I'm going wrong.
If there's an answer to this, I'm sorry, I missed it. The only thing I saw said to use Javascript, which is beyond my current skillset. Thanks.
The Code:
<!DOCTYPE html>
<html lang="en-US">
<head>
<!--link-->
<meta charset="UTF-8" />
<title>Sports Trivia</title>
</head>
<body>
<form>
<?php>
extract($_REQUEST);
include("triviaQuestions.php");
//functions
//Display Next Question template provided by Dan Brekke
function nextQuestion($trivia,&$used)
{
do
$num = rand(0,count($trivia)-1);
while ($used[$num]);
$used[$num] = true;
reset($trivia);
for ($i = 0; $i < $num; $i++)
next($trivia);
return key($trivia);
}
function displayQuestion($trivia,$count,&$used,$question)
{
if ($count < count($trivia))
{
$questionNum = $count+1;
echo <<< HERE
<h3>Question $questionNum:</h3>
<h3>$question</h3>
HERE;
}
else
$question = "You've reached the endzone!";
}
function displayButtons()
{
echo <<< HERE
<p>
<input type="submit" name="button" value="Next Question" />
<input type="submit" name="button" value="Quit" />
</p>
HERE;
}
function passData($trivia,$count,$used)
{
echo "<input type='hidden' name='count' value='$count'>";
for ($i = 0; $i < count($trivia); $i++)
echo "<input type='hidden' name='used[$i]' value='$used[$i]'>";
}
if ($button == NULL || $button == "New Game")
{
//variables
$used = NULL;
$count = 0;
$correct = 0;
echo <<< HERE
<h1>Sports Trivia!</h1>
<h3>Welcome to Sports Trivia. Enter your name and click Play to begin!</h3>
<h3>Name:
<input type="text" name="name" autocomplete="off" autofocus="on">
</h3>
<input type="submit" name="button" value="Play" />
<input type="submit" name="button" value="Display Scores" />
<br /><br />
Back To Home
HERE;
//experimenting, since I don't know how this works
serialize($trivia);
serialize($used);
}
else
{
if ($button == "Play")
{
$question = nextQuestion($trivia,$used);
displayQuestion($trivia,$count,$used,$question);
echo <<< HERE
<input type="text" name="answer" autocomplete="off" autofocus="on" />
<p>
<input type="submit" name="button" value="Enter" />
</p>
HERE;
}
else if ($button == "Enter")
{
echo $question;
}
}
echo <<< HERE
<input type="hidden" name=$helloWorld />
HERE;
?>
</form>
</body>
</html>

Trying to output data which has been input by user

I'm having issues trying to output data which a user has inputted into a form.. It's a 2 block form, I'm just trying to save the data into 2 variables and then echo the variables. But I don't understand where I'm going wrong. Any help appreciated.
<?php
echo $problem = "";
if(isset($_POST['submit']) && $_POST['submit']=="submit"){
if(!empty($_POST['eWeight']) && $_POST['eWeight']!=''){
$eWeight = mysqli_real_escape_string($conn, trim($_POST['eWeight']));
} else {
$problem .= "Please enter a weight. <br/>";
}
if(!empty($_POST['gym']) && $_POST['gym']!=''){
$gym = mysqli_real_escape_string($conn, trim($_POST['gym']));
} else {
$problem .= "Please enter time at gym. <br/>";
}
echo $eWeight, $gym;
}
?>
<?php
if($conn){
echo "connected";
}
echo $problem;
echo $eWeight;
?>
<form class="pure-form pure-form-stacked" name="contact_weight">
<label for="eWeight">Enter Weight: </label> <input type="number" id="eWeight" name="eWeight" placeholder="88" required/>
<label for="gym">Enter Time at Gym: </label> <input type="number" id="gym" name="gym" placeholder="60" required/>
<button class="submit" type="submit">Submit Form</button>
</form>
You can do something like this
<?php
echo $problem = "";
if(isset($_POST['submit'])){
if(!empty($_POST['eWeight']) && $_POST['eWeight']!=''){
$eWeight = mysqli_real_escape_string($conn, trim($_POST['eWeight']));
} else {
$problem .= "Please enter a weight. <br/>";
}
if(!empty($_POST['gym']) && $_POST['gym']!=''){
$gym = mysqli_real_escape_string($conn, trim($_POST['gym']));
} else {
$problem .= "Please enter time at gym. <br/>";
}
echo $eWeight, $gym;
}
if($conn){
echo "connected";
}
echo $problem;
echo $eWeight;
?>
<form class="pure-form pure-form-stacked" name="contact_weight" action="" method="post">
<label for="eWeight">Enter Weight: </label> <input type="number" id="eWeight" name="eWeight" placeholder="88" required/>
<label for="gym">Enter Time at Gym: </label> <input type="number" id="gym" name="gym" placeholder="60" required/>
<button name="submit" class="submit" type="submit">Submit Form</button>
</form>

Invite PHP form Using External Text File

REVISED: I'm trying to process a form, validates it and sends emails to these recipients.
<form>
<input name="name1"> <input email="email1">
<input name="name2"> <input email="email2">
<input name="name3"> <input email="email3">
....
<input type="submit" name="submit">
</form>
What I was trying to do was rather than doing a multiple inputs, I'd use the for loop like so..
<form method=GET action="">
<?php
for($i = 1; $i <= 10; $i++)
{
echo 'First name: <input name="firstname[$i]">';
echo 'Last name:<input name="lastname[$i]">';
echo 'Email: <input name="email[$i]"><br>';
}
?>
<input type="submit" name="Submit" value="Submit">
</form>
<?php
$msg = "a message";
$subject = "a subject";
foreach($_POST['email'] as $email){
mail($email, $subject,$msg,'From: ' . $_POST['sendername'] . "\n\r" );
}
?>
My question is I'm not sure what's the best way to validate these fields. Any pointers would be helpful. I'm not a programmer I'm just a beginner.
EDIT
The answer below is for the OP's original question before his EDIT.
Original question: https://stackoverflow.com/revisions/18454820/1
This line was problematic:
echo '<input type="text" name="firstname[]" size="20" value=".(if (isset($_POST['firstname'][$i])) { print htmlspecialchars($_POST['firstname'][$i]); })." />';
and was replaced by: (to get it working)
echo '<input type="text" name="firstname[]" size="20" />';
Plus, I replaced your form action to action=""
Working code:
<!DOCTYPE html>
<html>
<head>
<title>PHP FORM </title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="container">
<?php
// Print some introductory text:
print '<h2>Party Invitation Form</h2>
<p>Please enter list of people with first name, last name and email address to get an invitation by email.</p>';
// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$problem = FALSE; // No problems so far.
// Check for each value...
for ($i = 0; $i < count($_POST['email']); $i++) {
if (empty($_POST['firstname'][$i])) {
$problem = TRUE;
echo '<input type="text" name="firstname[]" size="20" />';
}
if (empty($_POST['lastname'][$i])) {
$problem = TRUE;
}
if (empty($_POST['email'][$i]) || (substr_count($_POST['email'][$i], '#') != 1) ) {
$problem = TRUE;
}
}
if (!$problem) { // If there weren't any problems...
// Print a message:
echo '<p><b>Thank you for registering! We will send each one an invitation: <b> </b></p>';
for ($i = 0; $i < count($_POST['email']); $i++) {
echo $_POST['firstname'][$i]." ".$_POST['lastname'][$i]." ".$_POST['email'][$i]." <br/>";
// Send the email:
$body = "Thank you {$_POST['firstname'][$i]} for registering with the blah blah blah blah!";
mail($_POST['email'][$i], 'Party Invitation', $body, 'From: email#example.com');
}
// Clear the posted values:
$_POST = array();
} else { // Forgot a field.
print '<p id="error">* Required field! Please try again. Thank you.</p>';
}
} // End of handle form IF.
// Create the form:
?>
<form action="" method="post">
<table>
<tr>
<td>First name:</td>
<td>Last name:</td>
<td>Email:</td>
</tr>
<?php for ($i = 0; $i < 2; $i++) { ?>
<tr>
<td><?php if ($problem == TRUE) { echo '<p id="error">*'; } ?>
<input type="text" name="firstname[]" size="20" value="<?php if (isset($_POST['firstname'][$i])) { print htmlspecialchars($_POST['firstname'][$i]); } ?>" />
</td>
<td><?php if ($problem == TRUE) { echo '<p id="error">*'; } ?>
<input type="text" name="lastname[]" size="20" value="<?php if (isset($_POST['lastname'] [$i])) { print htmlspecialchars($_POST['lastname'][$i]); } ?>" />
</td>
<td><?php if ($problem == TRUE) { echo '<p id="error">*'; } ?><input type="text" name="email[]" size="20" value="<?php if (isset($_POST['email'][$i])) { print htmlspecialchars($_POST['email'][$i]); } ?>" />
</td>
</tr>
<?php } ?>
<tr><td><p><input type="submit" class="button" name="submit" value="Register!" /></td>
</tr>
</table>
</form>
</div>
</body>
</html>

Categories