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>
Related
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>
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.
I've been doing a project for php, about sticky keys. It's quite straight forward. However I'm getting a few errors... I'm using CodeLobster.
Can anyone help me find my error on this ?
I've been looking for 2hrs now, I tried the debug, but I don't really know how to use it here.
Thank you so much. Any helps will be appreciated
This is what I am getting:
Output should be this:
<html><head><title>Empty Fields</title>
<body><div align="center">
<h2>Validating Input</h2>
<?php
$errors = array();
if(isset($_POST['submit'])){
validate_input();
if(count($errors) != 0){
display_form();
}
else{
echo "<b>OK! Go ahead and Process the form!</b><br/>";
}
}
else{
display_form();
}
function validate_input(){
global $errors;
if($_POST['name'] == ""){
$errors['name'] = "<font color='red'>***Your name?***</font>";
}
if($_POST['phone'] == ""){
$errors['phone'] = "<font color='red'>***Your phone?</font>";
}
}
function display_form(){
global $errors;
?>
<b>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
What is your name?<br/>
<input type="text" name="name" value="<?php echo $_POST['name']; ?>" /><br/>
<?php echo $errors['name']; ?><br/>
What is your phone number?<br/>
<input type="text" name="phone" value="<?php echo $_POST['phone']; ?>" /><br/>
<?php echo $errors['phone']; ?><br/>
<input type="reset" />
<input type="submit" name="submit" /><br/>
</form></b>
<?php
}
?>
</div>
</body>
</html>
Can you please check once this code:-
<html><head><title>Empty Fields</title>
<body><div align="center">
<h2>Validating Input</h2>
<?php
$errors = array();
if(isset($_POST['submit'])){
validate_input();
if(count($errors) != 0){
display_form();
}
else{
echo "<b>OK! Go ahead and Process the form!</b><br/>";
}
}
else{
display_form();
}
function validate_input(){
global $errors;
if($_POST['name'] == ""){
$errors['name'] = "Your name?";
}
if($_POST['phone'] == ""){
$errors['phone'] = "Your phone?";
}
}
function display_form(){
global $errors;
?>
<b>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
What is your name?<br/>
<input type="text" name="name" value="<?php if(isset($_POST['name'])){echo $_POST['name'];} ?>" /><br/>
<?php if(isset($errors['name'])){echo $errors['name'];} ?><br/>
What is your phone number?<br/>
<input type="text" name="phone" value="<?php if(isset($_POST['name'])){$_POST['phone'];} ?>" /><br/>
<?php if(isset($errors['phone'])){echo $errors['phone'];} ?><br/>
<input type="reset" />
<input type="submit" name="submit" /><br/>
</form></b>
<?php
}
?>
</div>
</body>
</html>
I try to revise your code, There are many point to fixed.
First, you need to keep $_POST['name'] and $_POST['phone'] in variable for easy to use in each function.
Like this,
$name = (isset($_POST['name']) ? $_POST['name'] : '');
$phone = (isset($_POST['phone']) ? $_POST['phone'] : '');
You also need to add code below to first line in function that need to use this variable
global $name;
global $phone;
In function display_form you need to check $errors['name'] and $errors['name'] is empty or not before print(echo) the line.
if (isset($errors['name'])) echo $errors['name'];
if (isset($errors['phone'])) echo $errors['phone'];
So, Finally the code should be like the below, I tried this code without error.
<html>
<head><title>Empty Fields</title>
<body>
<div align="center">
<h2>Validating Input</h2>
<?php
$errors = array();
$name = (isset($_POST['name']) ? $_POST['name'] : '');
$phone = (isset($_POST['phone']) ? $_POST['phone'] : '');
if(isset($_POST['submit']))
{
validate_input();
if(count($errors) != 0)
{
display_form();
}
else
{
echo "<b>OK! Go ahead and Process the form!</b><br/>";
}
}
else
{
display_form();
}
function validate_input(){
global $errors;
global $name;
global $phone;
if($name == '')
{
$errors['name'] = "<font color='red'>***Your name?***</font>";
}
if($phone == '')
{
$errors['phone'] = "<font color='red'>***Your phone?</font>";
}
}
function display_form(){
global $errors;
global $name;
global $phone;
?>
<b>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
What is your name?<br/>
<input type="text" name="name" value="<?php echo $name; ?>" /><br/>
<?php if (isset($errors['name'])) echo $errors['name']; ?><br/>
What is your phone number?<br/>
<input type="text" name="phone" value="<?php echo $phone; ?>" /><br/>
<?php if (isset($errors['phone'])) echo $errors['phone']; ?><br/>
<input type="reset" />
<input type="submit" name="submit" /><br/>
</form></b>
<?php
}
?>
</div>
</body>
</html>
Simply use isset($var); to avoid Undefined index: EROOR on php.
echo isset($_POST['name']);
echo isset($_POST['phone']);
wherever you need.
How do I echo the form input without having to re-display the form after validation? I can only display the input after the form. Here is the code I have
<?php
$postalCode = $_POST['postalCode'];
$postalCodeErr = "";
$postalCodeValidation = '/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/';
$postalCodeIsValid = false;
?>
<html>
<body>
INT322 Lab 3-1
<br />
<br />
<form name="lab3form" action="index.php" method="post">
Postal Code:
<input type="text" name="postalCode" value="<?php if(isset($postalCode)) echo $postalCode; ?>" />
<?php
if(($postalCode != "") && preg_match($postalCodeValidation, $postalCode)) {
$postalCodeIsValid = true;
}
else {
$postalCodeErr = "Invalid Postal Code";
}
if(isset($postalCode)) echo " $postalCodeErr";
?>
<br />
<br />
<input type="submit" name="submit" />
</form>
</body>
</html>
<?php
if($_POST['submit'] && $postalCodeIsValid) {
echo "Postal Code: $postalCode";
}
?>
How about wrapping your form in the else of if($_POST['submit'] && $postalCodeIsValid) { ... } else { ... }
<?php
if($_POST['submit'] && $postalCodeIsValid) {
echo "Postal Code: $postalCode";
}
else {
<form name="lab3form" action="index.php" method="post">
Postal Code:
<input type="text" name="postalCode" value="<?php if(isset($postalCode)) echo $postalCode; ?>" />
<?php
if(($postalCode != "") && preg_match($postalCodeValidation, $postalCode)) {
$postalCodeIsValid = true;
}
else {
$postalCodeErr = "Invalid Postal Code";
}
if(isset($postalCode)) echo " $postalCodeErr";
?>
<br />
<br />
<input type="submit" name="submit" />
</form>
}
?>
UPDATED ANSWER with full code:
<html>
<body>
INT322 Lab 3-1
<br />
<br />
<?php
if(!empty($_POST['submit'])):
$postalCode = $_POST['postalCode'];
if(isValidPostalCode($postalCode)):
echo "Postal Code: $postalCode";
else:
form($postalCode, true);
endif;
else:
form();
endif;
?>
</body>
</html>
<?php
function form($postalCode = null, $hasError = false) { ?>
<form name="lab3form" action="postal.php" method="post">
Postal Code:
<input type="text" name="postalCode" value="<?php if(isset($postalCode)) echo $postalCode; ?>" />
<?php if ($hasError): ?>
<div class="error">Invalid Postal Code</div>
<?php endif; ?>
<br />
<br />
<input type="submit" name="submit" />
</form>
<?php }
function isValidPostalCode($postalCode) {
$postalCodeValidation = '/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/';
return !empty($postalCode) && preg_match($postalCodeValidation, $postalCode);
}
?>
Please note that your regular expression only works with postal codes such as A1B2C3 - I'm not sure if this is the behavior you want.
How to clear page content and show other content after I validate and submit a form?
<?php
if(isset($_POST['Confirm'])) {
$to = "email#email.com";
$error = 0;
$first_name = $_POST['first_name'];
//Validation things
if(trim($first_name) == '') {$error = 1; $first_namerr = 1;}
$msg ="
First Name:$first_name
-------------------------
";
$sub ="Contact";
$from = "From: Support form";
#mail($to, $sub, $msg, $from);
//How to clear actual content and echo other ?
}
}
?>
<form name="contact" id="contact" method="post" action="<? echo $_SERVER['PHP_SELF']; ?>">
<label for="first_name" class="inner_text"><?php if ($error != 0){ if ($first_namerr == 1) {print("<font style='color: Red;'>");} }?>First Name<?php if ($error != 0){if ($first_namerr == 1) {print("</font>");}} ?></label>
<input id="first_name" name="first_name" size="30" type="text" value="<? echo $first_name; ?>" /><?php if ($error != 0){ if ($first_namerr == 1) {print('<img src="images/error.gif">');} }?>
<input type="submit" id="Confirm" name="Confirm" value="Confirm" />
</form>
I'm beginner in PHP, so please be explicit if you want to give an answer!
You could use an if/else statement to control the content being displayed - e.g:
<?php
if (isset($_POST['Confirm'])) {
// Your mail code
?>
Thank you, your message has been sent! <!-- This content is shown after form submission -->
<?php } else { ?>
<!-- Display your email form -->
<?php }; ?>