Why Can't I Pass a String? - php

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>

Related

PHP send variable value external webpage

I'm currently trying to send the two variable values, $incorrect and $correct from a form.
I have tried to use $_POST[] to create this functionality, yet it doesn't work!
Could anyone help me when creating such a functionality ?
page1.php
<form action="testresult.php" method="POST">
<label for="qn1">Question 1: <?php echo $array_question[$question_num_array[0]] ?></label><br>
<input type="text" id="question1_answer" name="question1_answer" required><br><br>
<label for="qn2">Question 2: <?php echo $array_question[$question_num_array[1]] ?></label><br>
<input type="text" id="question2_answer" name="question2_answer" required><br><br>
<label for="qn3">Question 3: <?php echo $array_question[$question_num_array[2]] ?></label><br>
<input type="text" id="question3_answer" name="question3_answer" required><br><br>
<input type="hidden" name="correct" id="correct" value="<?php $correct ?>" />
<input type="hidden" name="incorrect" id="incorrect" value="<?php $incorrect ?>" />
<input type="submit" name="submitAnswers" value="Submit">
</form>
<?php
if(isset($_POST["submitAnswers"])){
$correct = 0;
$incorrect = 0;
$qn1_ans = $_POST['question1_answer'];
$qn2_ans = $_POST['question2_answer'];
$qn3_ans = $_POST['question3_answer'];
if ($qn1_ans == $array_answer[$question_num_array[0]]){ $correct ++; }
else { $incorrect ++; }
if ($qn2_ans == $array_answer[$question_num_array[1]]){ $correct ++; }
else { $incorrect ++; }
if ($qn3_ans == $array_answer[$question_num_array[2]]){ $correct ++; }
else { $incorrect ++; }
}
?>
And on the receiving end
page2.php
<html>
<head>
<title>Results</title>
</head>
<body>
<?php
$correct = $_POST['correct'];
$incorrect = $_POST['incorrect'];
echo $correct."test ".$incorrect;
?>
</body>
</html>
Your first page should JUST show the questions, it will be like this.
<form action="testresult.php" method="POST">
<label for="qn1">Question 1: <?php echo $array_question[$question_num_array[0]] ?></label><br>
<input type="text" id="question1_answer" name="question1_answer" required><br><br>
<label for="qn2">Question 2: <?php echo $array_question[$question_num_array[1]] ?></label><br>
<input type="text" id="question2_answer" name="question2_answer" required><br><br>
<label for="qn3">Question 3: <?php echo $array_question[$question_num_array[2]] ?></label><br>
<input type="text" id="question3_answer" name="question3_answer" required><br><br>
<!--input type="hidden" name="correct" id="correct" value="<?php $correct ?>" />
<input type="hidden" name="incorrect" id="incorrect" value="<?php $incorrect ?>" /-->
<input type="submit" name="submitAnswers" value="Submit">
</form>
When you hit the submit button, the answers are posted to testresult.php.
In this file, first checking the answers, then showing the result.
The page doesn't contain questions, so you need to include the php file too.
<html>
<head>
<title>Results</title>
</head>
<body>
<?php
if(isset($_POST["submitAnswers"])){
include 'question.php'; #include the question array.
$correct = 0;
$incorrect = 0;
$qn1_ans = $_POST['question1_answer'];
$qn2_ans = $_POST['question2_answer'];
$qn3_ans = $_POST['question3_answer'];
if ($qn1_ans == $array_answer[$question_num_array[0]]){ $correct ++; }
else { $incorrect ++; }
if ($qn2_ans == $array_answer[$question_num_array[1]]){ $correct ++; }
else { $incorrect ++; }
if ($qn3_ans == $array_answer[$question_num_array[2]]){ $correct ++; }
else { $incorrect ++; }
echo $correct."test ".$incorrect;
}
?>
</body>
</html>
Where did those variables from from?
In your code you're calling two vars $array_answer and $question_num_array.
None of these two variables are set! Please fix this issue.
The Form action you've set to your testresult.php. So surely the form will carry all of its data to that page. But you are trying to get the data on the same page as if(isset($_POST["submitAnswers"])) where is the form; what actually should exist in that testresult.php page. So should be like this:
index.php or something.php
<form action="testresult.php" method="POST">
<label for="qn1">Question 1: <?php echo $array_question[$question_num_array[0]] ?></label><br>
<input type="text" id="question1_answer" name="question1_answer" required><br><br>
<label for="qn2">Question 2: <?php echo $array_question[$question_num_array[1]] ?></label><br>
<input type="text" id="question2_answer" name="question2_answer" required><br><br>
<label for="qn3">Question 3: <?php echo $array_question[$question_num_array[2]] ?></label><br>
<input type="text" id="question3_answer" name="question3_answer" required><br><br>
<input type="hidden" name="correct" id="correct" value="<?php $correct ?>" />
<input type="hidden" name="incorrect" id="incorrect" value="<?php $incorrect ?>" />
<input type="submit" name="submitAnswers" value="Submit">
</form>
testresult.php
<?php
// questions array that is called in the form's page should be
called here too to get the questions and comparisons.
if (isset($_POST['submitAnswers'])) {
$correct = 0;
$incorrect = 0;
$qn1_ans = $_POST['question1_answer'];
$qn2_ans = $_POST['question2_answer'];
$qn3_ans = $_POST['question3_answer'];
if ($qn1_ans == $array_answer[$question_num_array[0]]) {
$correct++;
} else {
$incorrect++;
}
if ($qn2_ans == $array_answer[$question_num_array[1]]) {
$correct++;
} else {
$incorrect++;
}
if ($qn3_ans == $array_answer[$question_num_array[2]]) {
$correct++;
} else {
$incorrect++;
}
}
?>
<html>
<head>
<title>Results</title>
</head>
<body>
<?php
$correct = $_POST['correct'];
$incorrect = $_POST['incorrect'];
echo $correct . 'test ' . $incorrect;
?>
</body>
</html>

Adding values to Text Area

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.

PHP help me with this some notifications

I'm having a hard time figuring how to fix this notification. I already did it but the result was the code didn't work. My logic is not that high here is the code:
Here is the error.
Would you also explain why the gender is undeinfed but the textbox and textarea was just fine?
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
if(isset($_POST['submit'])){
$x=$_POST['name'];
$y=$_POST['email'];
$z=$_POST['website'];
$c=$_POST['comment'];
$v=$_POST['gender'];
if($x == '' or $y == '' or $z==''or $c=='' or $v==''){
echo "* required all fields";
}else{
$result=$x.'<br>'.$y.'<br>'.$z.'<br>'.$c.'<br>'.$v;
}
}
?>
<form action="" method="post">
NAME:<input type="text" name="name"><br><br>
EMAIL:<input type="text" name="email"><br><br>
WEBSITE:<input type="text" name="website"><br><br>
<textarea name="comment" rows="5" cols="40"></textarea><br><br>
GENDER:<input type="radio" name="gender" value="Male">MALE
<input type="radio" name="gender" value="Female">Female<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h3>YOUR INPUT:</h3>";
echo $result;
?>
</body>
</html>
if($x == '' ||$y == '' || $z=='' || $c=='' || $v==''){
echo "* required all fields";
}else{
You cant user or man check the PHP manual
try this way
if(($x="" || empty($x))&&($y="" || empty($y))&&($z="" || empty($z)))
{
echo "* required all fields";
}
may be it will help
What you need is a JS function to validate your radio buttons at first, or you could also use the HTML attribute required (I have written both of them) followed by only a few if-statements This should work just fine.
<!DOCTYPE HTML>
<html>
<head>
<script>
function validateForm(){
for(i=0; i<document.form.radios.length; i++){
if(document.form.radios[i].checked==false){
c=1;
}
else{
c=0;
break;
}}
if(c==1){
alert('Please select an option');
}
}
</script>
</head>
<body>
<?php
if(isset($_POST['submit'])){
$x=$_POST['name'];
$y=$_POST['email'];
$z=$_POST['website'];
$c=$_POST['comment'];
if($x == '' or $y == '' or $z==''or $c=='')
{ echo "* required all fields";
}else{
$result=$x.'<br>'.$y.'<br>'.$z.'<br>'.$c;
}
}
?>
<form action="" method="post">
NAME:<input type="text" name="name"><br><br>
EMAIL:<input type="text" name="email"><br><br>
WEBSITE:<input type="text" name="website"><br><br>
<textarea name="comment" rows="5" cols="40"></textarea><br><br>
<input type="radio" name="gender" value="Male" required /> Male
<input type="radio" name="gender" value="Female" /> Female
<input type="submit" name = "submit" value="SAVE" />
</form>
<?php
if(isset($_POST['submit']))
{
if(!($x == '' or $y == '' or $z==''or $c=='')){
echo "<h3>YOUR INPUT:</h3>";
echo $result;
}else
echo "NOT ALL FIELDS WERE SELECTED.";}
?>
</body>
</html>
You have some undefined variables.In order to make it work try this:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$result = '';
$x = '';
$y = '';
$z = '';
$c = '';
$v = '';
if(isset($_POST['submit'])){
if(isset($_POST['name'])){
$x= $_POST['name'];
}
if(isset($_POST['email'])){
$y=$_POST['email'];
}
if(isset($_POST['website'])){
$z=$_POST['website'];
}
if(isset($_POST['comment'])){
$c=$_POST['comment'];
}
if(isset($_POST['gender'])){
$v=$_POST['gender'];
}
.......
But you should separate your HTML code from the PHP,
maybe creating and index.html and from.php file.
Keeping all into the same file is a very bad practice.
$v=isset($_POST['gender'])?$_POST['gender']:'';

PHP - Processing after input is entered twice in a row

I have a problem with my form.
I have an HTML Form as follows:
<form action="index.php" method="post">
<input type="text" name="text" id="text">
<input type="submit" value="Send" name="send">
</form>
Now my problem is:
Every time I process this form for the first time, it should output an error. The error has to be shown every time, if this is the first try.
If I enter the same input value twice, it should succeed.
I thought about setting a session variable $_SESSION['first_visit] if I'm processing the form for the first time.
I also thought about saving the $_POST['text'] - Value into Session but it's being overwritten every time.
Thank you for your answers.
<?php
extract($_POST);
if( isset($send) )
{
if( $fired <= 0 )
{
$fired++;
echo "Nope, error. send again to succeed";
}
else
{
echo "Yay success";
}
}
?>
<form action="" method="post">
<input type="hidden" name="fired" value="<?php echo isset($fired) ? $fired : 0 ?>">
<input type="text" name="text" id="text">
<input type="submit" value="Send" name="send">
</form>
Here's some quick and dirty snippet. We set a hidden input field with an initial value of 0 and count it up everytime the form has been send. The only thing to do afterwards is to check if the value of the hidden field is bigger than 0
You can use cookies instead of session
<form action="index.php" method="post" id="exampleForm">
<input type="text" name="text" id="text">
<input type="button" value="Send" name="send" onClick="checkVisit()">
</form>
<script>
function checkVisit(){
var isFirstVisit = getCookie("first_visit");
if(isFirstVisit == "" || isFirstVisit == 1){
setCookie("first_visit",0,1);
}else if (isFirstVisit == 0){
setCookie("first_visit",1,1);
document.getElementById("myForm").submit();
}
}
</script>
Thanks for this fast Answer! Your Tipp helped me with my problem a lot.
Here is the working Script:
<?php
session_start();
if(isset($_POST['go'])) {
$text = $_POST['text'];
$fired = $_POST['fired'];
if($fired <= 0) {
$fired++;
echo "Nope";
$_SESSION['val'] = $_POST['text'];
}
else {
if($fired > 0 && $_SESSION['val'] == $_POST['text'] ) {
echo "Success";
}
else {
echo "Failed";
$_SESSION['val'] = $_POST['text'];
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="test2.php" method="post">
<input type="text" name="text" id="text">
<input type="hidden" name="fired" value="<?php echo isset($fired) ? $fired : 0 ?>">
<input type="hidden" name="val" id="val" value="">
<input type="submit" value="Senden" name="go">
</form>
</body>
</html>

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