I am new to the world of coding and PHP. Having picked up some of the basics, I have put a form together. I'm sure there are much efficient ways to code a page however seeing I have put something together with what I have learnt so far, I am having troubling getting past on select a multi-select dropdown after the user has posted the page i.e. to remember what the user selected. Here is my entire code.
<?php
//Process form variables
//Validate if the form has been submitted
if(isset($_POST['submit'])) {
//Validate if the form elements were completed
$fname = isset($_POST['fname']) ? $_POST['fname'] : '';
$lname = isset($_POST['lname']) ? $_POST['lname'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';
$gender = isset($_POST['gender']) ? $_POST['gender'] : '';
$updates = isset($_POST['updates']) ? $_POST['updates'] : '';
$media = isset($_POST['media']) ? $_POST['media'] : '';
$comments = isset($_POST['comments']) ? $_POST['comments'] : '';
//Place error messages in an array
$errormsg = array();
if(empty($fname)) {
$errormsg[0] = 'Please specify your first name. It\'s blank.';
}
if(empty($lname)) {
$errormsg[1] = 'Please specify your last name. It\'s blank.';
}
if(empty($email)) {
$errormsg[2] = 'Please provide an email address. It\'s blank.';
}
if(empty($gender)) {
$errormsg[3] = 'Please select a gender. It\'s blank.';
}
if(empty($updates)) {
$errormsg[4] = 'Please select how we can contact you. It\'s blank.';
}
if(empty($media)) {
$errormsg[5] = 'Please select where you heard about us. It\'s blank.';
}
if(empty($comments)) {
$errormsg[6] = 'Please tell us what you think of us. It\'s blank.';
}
//Return list of error messages
foreach($errormsg as $errormsg) {
echo $errormsg . '<br />';
}
//Debug
print_r($_POST['media']);
}
?>
<html>
<head>
<title>Sample Registration Form</title>
</head>
<body>
<h2>Sample Registration Form</h2>
<form name="registration" method="post" action="registration.php">
<div>
First Name: <br />
<input type="text" name="fname" value="<?php if(!empty($_POST['fname'])) { echo $fname; } ?>">
</div>
<div>
Last Name: <br />
<input type="text" name="lname" value="<?php if(!empty($_POST['lname'])) { echo $lname ; } ?>">
</div>
<div>
Email Address: <br />
<input type="text" name="email" value="<?php if(!empty($_POST['email'])) { echo $email; } ?>">
</div>
<div>
Gender: <br />
<?php
//Generate gender array
$gender = array('male', 'female');
$countgender = count($gender);
for($start=0;$start < $countgender;$start=$start+1) {
$status = '';
if(isset($_POST['submit'])) {
if($_POST['gender'][0] == $gender[$start]) {
$status = 'checked';
// echo $gender[$start];
}
}
$genderform = '<input type="radio" name="gender[]" value="'. $gender[$start] . '" '. $status. '>' . $gender[$start];
echo $genderform;
}
// foreach($gender as $gender) {
// $status = '';
// if(isset($_POST['submit'])) {
// if($_POST['gender'][0] == $gender) {
// $status = 'checked';
// }
// }
// $genderform = '<input type="radio" name="gender[]" value="' .$gender . '" ' . $status .'>'. $gender . '';
// echo $genderform;
// }
?>
</div>
<div>
Would you like to receive updates from us? <br />
<?php
$updates = array(0 => 'newsletter', 1 => 'email', 2 => 'sms');
foreach($updates as $updatekeys => $updatevalues) {
$status = '';
if(!empty($_POST['updates'][$updatevalues]) == $updatevalues) {
$status = 'checked';
// echo $_POST['updates'][$updatevalues];
}
echo '<input type="checkbox" name="updates[' . $updatevalues . ']" value="'. $updatevalues. '" '. $status . '>'.$updatevalues;
}
?>
</div>
<div>
How did you hear about us? <br />
<select name="media[]" multiple>
<?php
$media = array(0 => 'internet', 1 => 'pamphlet', 2 => 'brochure');
foreach($media as $mediakey => $mediavalue) {
$mediaform = '<option value="'. $mediavalue . '">'.$mediavalue.'</option>';
echo $mediaform;
}
?>
</select>
</div>
<div>
Tell us what you think: <br />
<textarea name="comments" cols="50" rows="10"><?php if(!empty($_POST['comments'])) { echo $comments; } ?></textarea>
</div>
<div>
<input type="submit" name="submit" value="submit">
</div>
</form>
</body>
</html>
EDIT
Guys, I have updated my code to reflect some of the suggestions below. Let me know if the page is better coded. I have not included suggestions such as $start++ just because I am trying to understand what it means. I love to make coding as short as possible but seeing that I am just learning, best to get a good foundation.
<?php
//Initialize session
session_start();
//Generate session id
echo session_id() . '<br />';
//Process form variables
//Validate if the form has been submitted
if(isset($_POST['submit'])) {
//Validate if the form elements were completed
$fname = isset($_POST['fname']) ? $_POST['fname'] : '';
$lname = isset($_POST['lname']) ? $_POST['lname'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';
$gender = isset($_POST['gender']) ? $_POST['gender'] : '';
$updates = isset($_POST['updates']) ? $_POST['updates'] : '';
$media = isset($_POST['media']) ? $_POST['media'] : '';
$comments = isset($_POST['comments']) ? $_POST['comments'] : '';
//Place error messages in an array
$errormsg = array();
if(empty($fname)) {
$errormsg[0] = 'Please specify your first name. It\'s blank.';
}
if(empty($lname)) {
$errormsg[1] = 'Please specify your last name. It\'s blank.';
}
if(empty($email)) {
$errormsg[2] = 'Please provide an email address. It\'s blank.';
}
if(empty($gender)) {
$errormsg[3] = 'Please select a gender. It\'s blank.';
}
if(empty($updates)) {
$errormsg[4] = 'Please select how we can contact you. It\'s blank.';
}
if(empty($media)) {
$errormsg[5] = 'Please select where you heard about us. It\'s blank.';
}
if(empty($comments)) {
$errormsg[6] = 'Please tell us what you think of us. It\'s blank.';
}
//Return list of error messages
foreach($errormsg as $errormsg) {
echo $errormsg . '<br />';
}
//Debug
// print_r($_POST['media']);
}
?>
<html>
<head>
<title>Sample Registration Form</title>
</head>
<body>
<h2>Sample Registration Form</h2>
<form name="registration" method="post" action="registration.php">
<div>
First Name: <br />
<input type="text" name="fname" value="<?php if(!empty($_POST['fname'])) { echo $fname; } ?>">
</div>
<div>
Last Name: <br />
<input type="text" name="lname" value="<?php if(!empty($_POST['lname'])) { echo $lname ; } ?>">
</div>
<div>
Email Address: <br />
<input type="text" name="email" value="<?php if(!empty($_POST['email'])) { echo $email; } ?>">
</div>
<div>
Gender: <br />
<?php
//Generate gender array
$gender = array('male', 'female');
$countgender = count($gender);
for($start=0;$start < $countgender;$start=$start+1) {
$status = '';
if(isset($_POST['submit']) && !empty($_POST['gender'])) {
$status = in_array($gender[$start], $_POST['gender']) ? 'checked' : '';
}
$genderform = '<input type="radio" name="gender[]" value="'. $gender[$start] . '" '. $status. '>' . $gender[$start];
echo $genderform;
}
?>
</div>
<div>
Would you like to receive updates from us? <br />
<?php
$updates = array(0 => 'newsletter', 1 => 'email', 2 => 'sms');
foreach($updates as $updatekeys => $updatevalues) {
$status = '';
if(isset($_POST['submit']) && !empty($_POST['updates'])) {
$status = in_array($updatevalues, $_POST['updates']) ? 'checked' : '';
}
// if(!empty($_POST['updates'][$updatevalues]) == $updatevalues) {
// $status = 'checked';
// echo $_POST['updates'][$updatevalues];
// }
echo '<input type="checkbox" name="updates[' . $updatevalues . ']" value="'. $updatevalues. '" '. $status . '>'.$updatevalues;
}
?>
</div>
<div>
How did you hear about us? <br />
<select name="media[]" multiple>
<?php
$media = array(0 => 'internet', 1 => 'pamphlet', 2 => 'brochure');
foreach($media as $mediakey => $mediavalue) {
$status = in_array($mediavalue,$_POST['media'])? 'selected' : '';
$mediaform = '<option value="'. $mediavalue . '" '. $status .'>'.$mediavalue.'</option>';
echo $mediaform;
}
?>
</select>
</div>
<div>
Tell us what you think: <br />
<textarea name="comments" cols="50" rows="10"><?php if(!empty($_POST['comments'])) { echo $comments; } ?></textarea>
</div>
<div>
<input type="submit" name="submit" value="submit">
</div>
</form>
</body>
</html>
You can use in_array function to check whether the current $mediavalue in the array of selected $media - but you need to select another name for array with media sources, because it overwrites the $media variable with user selection. For example:
$mediaTypes = array(0 => 'internet', 1 => 'pamphlet', 2 => 'brochure');
foreach($mediaTypes as $mediakey => $mediavalue) {
$mediaform = '<option value="'. $mediavalue . '" '
. (in_array($mediavalue, $media) ? 'selected' : '') . '>' . $mediavalue.'</option>';
echo $mediaform;
}
There are a few recommended minor modifications to you code as well:
you do not need to use numbers in array - it duplicates the default behavior, so $mediaTypes = array(0 => 'internet', 1 => 'pamphlet', 2 => 'brochure'); can be just $mediaTypes = array('internet', 'pamphlet', 'brochure');
when gender is not set, $_POST['gender'] causes notice "Undefined index: gender".
$start=$start+1 can be compacted to $start++;
it is better to reuse the variables with user inputs instead of accessing $_POST directly
Try this:
foreach($media as $mediakey => $mediavalue) {
$selected=in_array($mediavalue,$_POST['media'])?"selected":"";
$mediaform = '<option '.$selected.' value="'. $mediavalue . '">'.$mediavalue.'</option>';
echo $mediaform;
}
based on form output of the dropdown, set a $_SESSION['variable'] the do something like:
if (isset($_SESSION['variable'])) {
// if exists
}
else {
// if doesn't exist
}
you could even include other elseif statements based on different parameters. Then use else as an error handle.
Related
I'm trying to figure out how to apply a conditional to check if a year is a Leap year or Not. But when I add the leap function it just does not work.
Any idea how to make it work?
This is my code :
<?php
$name = "";
$character = "";
$email = "";
$birth_year = 1969;
$validation_error = "";
$existing_users = ["admin", "guest"];
$options = ["options" => ["min_range" => 1920, "max_range" => date("Y")]];
function leap($year) {
date('L', strtotime("$year-01-01")) ? TRUE : FALSE;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$raw_name = trim(htmlspecialchars($_POST["name"]));
if (in_Array($raw_name,$existing_users)){
$validation_error .= "This name is taken. <br>";
} else {
$name = $raw_name;
}
$raw_character = $_POST["character"];
if (in_array($raw_character,["wizard", "mage", "orc"])) {
$character = $raw_character;
} else {
$validation_error .= "You must pick a wizard, mage, or orc. <br>";
}
$raw_email = $_POST["email"];
if (filter_var($raw_email,FILTER_VALIDATE_EMAIL)) {
$email = $raw_email;
} else {
$validation_error .= "Invalid email. <br>";
}
$raw_birth_year = $_POST["birth_year"];
if (filter_var($raw_birth_year,FILTER_VALIDATE_INT,$options)){
$birth_year = $raw_birth_year;
if ($raw_character === "mage") {
if (!leap($birth_year)){
$validation_error .= "Mages have to be born on leap years. <br>";
}}
} else {
$validation_error .= "That can't be your birth year. <br>";
}
}
?>
<h1>Create your profile</h1>
<form method="post" action="">
<p>
Select a name: <input type="text" name="name" value="<?php echo $name;?>" >
</p>
<p>
Select a character:
<input type="radio" name="character" value="wizard" <?php echo ($character=='wizard')?'checked':'' ?>> Wizard
<input type="radio" name="character" value="mage" <?php echo ($character=='mage')?'checked':'' ?>> Mage
<input type="radio" name="character" value="orc" <?php echo ($character=='orc')?'checked':'' ?>> Orc
</p>
<p>
Enter an email:
<input type="text" name="email" value="<?php echo $email;?>" >
</p>
<p>
Enter your birth year:
<input type="text" name="birth_year" value="<?php echo $birth_year;?>">
</p>
<p>
<span style="color:red;"><?= $validation_error;?></span>
</p>
<input type="submit" value="Submit">
</form>
<h2>Preview:</h2>
<p>
Name: <?=$name;?>
</p>
<p>
Character Type: <?=$character;?>
</p>
<p>
Email: <?=$email;?>
</p>
<p>
Age: <?=date("Y")-$birth_year;?>
</p>
Im using this function to find if a year is Leap or not
function leap($year) {
date('L', strtotime("$year-01-01")) ? TRUE : FALSE;
}
And this is the conditional that does not work :(
if ($raw_character === "mage") {
if (!leap($birth_year)){
$validation_error .= "Mages have to be born on leap years. <br>";
}}
I think your problem is the function is not returning anything, try :
function leap($year) {
return date('L', strtotime("$year-01-01")) ? TRUE : FALSE;
}
I am trying to display form information with Shipping Information Heading, with validation of name, contact etc. I am able to display it but not able to validate it and if I submit a form blank it shows blank values except payment and shipping method are displaying with default values selected and one more thing it is not showing errors i.e; fname is required, I am confused a little bit. Can anyone add one things that if anyone post blank form it redirect it to again to form2.php page?
This is my form2.php page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="welcome2.php" method="post">
<label>First name: </label>
<input type="text" name="fname"><br>
<label>Lastname name: </label>
<input type="text" name="lname"><br>
<label>Email: </label>
<input type="email" name="email"><br>
<label>Contact No </label>
<input type="text" name="cno"><br>
<label>Address </label>
<input type="text" name="addr"><br>
<label>City </label>
<input type="text" name="city"><br>
<label>State </label>
<input type="text" name="state"><br>
<label>Country </label>
<input type="text" name="country"><br>
<label>Zip Code </label>
<input type="text" name="zipcode"><br>
<label>Credit Card Number </label>
<input type="text" name="ccno"><br>
<label>Payment Option </label>
<select name="Payment_option">
<option value="Cash On Delivery">Cash On Delivery</option>
<option value="Online">Online</option>
</select> <br>
<label>Shipping Method </label>
<select name="Shipping_Method">
<option value="TCS">TCS</option>
<option value="Leapord">Leapord</option>
<option value="FEDEX">FEDEX</option>
</select> <br>
<button type="submit" name="sub">Submit</button>
</form>
<?php
if(isset($_SESSION['errors']))
{
foreach($_SESSION['errors'] as $key => $error)
{
echo $error."<br>";
}
unset($_SESSION['errors']);
}
?>
</body>
</html>
and this is my welcome2.php page
<?php session_start();
$fname = "";
$lname = "";
$email = "";
$cno = "";
$addr = "";
$city = "";
$state = "";
$country = "";
$zipcode = "";
$ccno = "";
extract($_POST);
$errors = array();
if(isset($_POST['fname'])){
$_SESSION['fname'] = $_POST['fname'];
}if(isset($_POST['lname'])){
$_SESSION['lname'] = $_POST['lname'];
}if(isset($_POST['email'])){
$_SESSION['email'] = $_POST['email'];
}if(isset($_POST['cno'])){
$_SESSION['cno'] = $_POST['cno'];
}if(isset($_POST['addr'])){
$_SESSION['addr'] = $_POST['addr'];
}if(isset($_POST['city'])){
$_SESSION['city'] = $_POST['city'];
}if(isset($_POST['state'])){
$_SESSION['state'] = $_POST['state'];
}if(isset($_POST['country'])){
$_SESSION['country'] = $_POST['country'];
}if(isset($_POST['zipcode'])){
$_SESSION['zipcode'] = $_POST['zipcode'];
}if(isset($_POST['ccno'])){
$_SESSION['ccno'] = $_POST['ccno'];
}
if(isset($_POST['sub']))
{
if(!$fname)
$errors[] = "First name is required";
}
if(!$lname)
{
$errors[] = "Last name is required";
}
if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
$errors = "Only letters and white space allowed";
}
if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
$errors = "Only letters and white space allowed";
}
if(!$email)
{
$errors[] = "Email is required";
}
if(!$cno)
{
$errors[] = "Contact is required";
}if (strlen($cno)<=5)
{
$errors[] ="Contact contain more than 11 characters";
}
if(!$addr)
{
$errors[] = "Address is required";
}
if(!$city)
{
$errors[] = "City is required";
}
if(!$state)
{
$errors[] = "State is required";
}
if(!$country)
{
$errors[] = "Country is required";
}
if(!$zipcode)
{
$errors[] = "Zip Code is required";
}
if(!$ccno)
{
$errors[] = "Credit Card Number is required";
}?>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1> Shipping Information </h1>
<?php echo $fname; echo "<br>";
echo $lname; echo "<br>";
echo $email; echo "<br>";
echo $cno; echo "<br>";
echo $addr; echo "<br>";
echo $city; echo "<br>";
echo $state; echo "<br>";
echo $country; echo "<br>";
echo $zipcode; echo "<br>";
echo $ccno; echo "<br>";
$option1 = isset($_POST['Payment_option']) ? $_POST['Payment_option'] : false;
if ($option1) {
echo htmlentities($_POST['Payment_option'], ENT_QUOTES, "UTF-8");
} else {
echo "Payment Method is required";
} echo "<br>";
$option2 = isset($_POST['Shipping_Method']) ? $_POST['Shipping_Method'] : false;
if ($option2) {
echo htmlentities($_POST['Shipping_Method'], ENT_QUOTES, "UTF-8");
} else {
echo "Shipping Method is required";
}
?>
You set the values at the top of the PHP file, so they are always set. Then the errors never trigger because you do not check if the $_POST[<value>] is set and then assign it to the variable.
Also, try to use loops. It helps with code maintenance and readability. Something like this could work for you:
$values = [
'fname' => 'First Name',
'lname' => 'Last Name',
'email' => 'Email',
'test' => 'testt',
];
$results = array();
$errors = array();
foreach ( $values as $name => $displayName ) {
if ( isset( $_POST[ $name ] ) )
{
$results[ $name ] = $_POST[ $name ];
}
else
{
$errors[] = $displayName . ' is required';
}
}
Your errors are being added with a faulty check. Use empty($variable) instead of the NOT operator (!).
Also, be careful how you are changing the value of your original empty variables.. I would use extract( $_POST, EXTR_OVERWRITE, 'form_' ); to be even safer and then reference by $form_fname, etc. Then use the empty() check.
I also recommend using a debugger that can step through each line with you. It works wonders.
I created the fields that has validation process like required fields, numbers only and valid email.
it displays the errors simultaneously after submit but upon changing only one of the fields, it accepts and does not revalidate the other.
example
name = Error : required field
telephone = Error : numbers only
email = Error : not a valid email
after i corrected only the email , it accepts and proceed on submitting without rechecking the others.
please see my code . thanks in advance
<?php
include("conn/db.php");
function renderForm($name ='', $tel = '', $email ='', $error='', $error2='', $error3='')
{
?>
<html >
<head> <title>Form</title></head>
<body>
<?php
if ($error != '') {
echo $error
}
if ($error2 != '') {
echo $error2;
}
if ($error3 != '') {
echo $error3;
}
?>
<form action="" method="post">
Name : <input type = "text" class = "form-control" name = "name_text" value="<?php echo $name; ?>"> <br/>
Tel :<input type = "text" class = "form-control" name = "tel_text" value="<?php echo $tel; ?>"> <br/>
Email :<input type ="text" class = "form-control " name = "email_text" value="<?php echo $email; ?>" > <br/>
<input name= "submit" type="submit" value="Update" class = "btn btn-primary" >
</form>
</body>
</html>
<?php
}
if (isset($_POST['submit'])){
$name = $_POST['name_text'];
$tel = $_POST['tel_text'];
$email = $_POST['email_text'];
if ($name== '' ){
$error = 'ERR: required field';
}
if(!is_numeric($telephone)){
$error2 = 'ERR: numbers only';
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error3 = 'ERR: Email not valid';
}
else
{
***WILL PROCESS THE SQL QUERY ***
header("Location: main.php");
}
renderForm($name, $tel , $email ,$error, $error2, $error3);
}
else{
renderForm();
}
$con->close();
?>
<?php
include("conn/db.php");
function renderForm($name ='', $tel = '', $email ='', $error='', $error2='', $error3='')
{
?>
<html >
<head> <title>Form</title></head>
<body>
<?php
if ($error != '') {
echo $error
}
if ($error2 != '') {
echo $error2;
}
if ($error3 != '') {
echo $error3;
}
?>
<form action="" method="post">
Name : <input type = "text" class = "form-control" name = "name_text" value="<?php echo $name; ?>"> <br/>
Tel :<input type = "text" class = "form-control" name = "tel_text" value="<?php echo $tel; ?>"> <br/>
Email :<input type ="text" class = "form-control " name = "email_text" value="<?php echo $email; ?>" > <br/>
<input name= "submit" type="submit" value="Update" class = "btn btn-primary" >
</form>
</body>
</html>
<?php
}
if (isset($_POST['submit'])){
$name = $_POST['name_text'];
$tel = $_POST['tel_text'];
$email = $_POST['email_text'];
$is_valid = true;
if ($name== '' ){
$error = 'ERR: required field';
$is_valid = false;
}
if(!is_numeric($telephone)){
$error2 = 'ERR: numbers only';
$is_valid = false;
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error3 = 'ERR: Email not valid';
$is_valid = false;
}
if($is_valid) {
***WILL PROCESS THE SQL QUERY ***
header("Location: main.php");
}
renderForm($name, $tel , $email ,$error, $error2, $error3);
}
else{
renderForm();
}
$con->close();
?>
Its just a small mistake:
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error3 = 'ERR: Email not valid';
} else {
***WILL PROCESS THE SQL QUERY ***
header("Location: main.php");
}
You only checked the email and if it is corecct it was proceding. It did not include the other 2 checks for name and number.
I added a small variable to check if all 3 are correct.
i try to challenge my self but i stuck(
I try to create a php form with 2 steps confirmation:
When the user fill up the form and hit Submit, it checks all the conditions(name, pass etc.). If everything ok automatically redirecting the user.
After redirecting (to the same page) the user can check all the details again.
If they ok, hit again the submit button which redirects to the final page.
I stuck on the 2nd phase...how to redirect to the final page?
I'm very beginner so i'm curios what could be done better or any advise.
<?php
// the php code
session_start();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// setting up the variables
$title = $_POST['title'];
$fName = trim(filter_input(INPUT_POST,'fName', FILTER_SANITIZE_STRING));
$lName = trim(filter_input(INPUT_POST,'lName',FILTER_SANITIZE_STRING));
$age = intval($_POST['age']);
$_SESSION['title'] = $title;
$_SESSION['fName'] = $fName;
$_SESSION['lName'] = $lName;
$_SESSION['age'] = $age;
//checking for possible errors
if ( $fName == "" || strlen($fName) <= 2 ) {
$errorMsg1 = "<span>Provide your First name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $lName == "" || strlen($lName) <= 2 ) {
$errorMsg2 = "<span>Provide your Last name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $age < 18 ) {
$errorMsg3 = "<span>You must be 18 or above!</span>";
$status = false;
}
else { $status = true; }
// redirecting to done page
if ($status) {
header("Location:TEST ZONE.php?status=awaiting");
}
}
?>
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<div id="wrapper">
<?php
if ( isset($_GET['status']) && $_GET['status'] == "awaiting" ) {
echo "<form>"
. "Check your Details!<br>"
. $_SESSION['title'] . "<br>"
. $_SESSION['fName'] . "<br>"
. $_SESSION['lName'] . "<br>"
. $_SESSION['age'] . "<br>"
// **NOW WHEN I'M in the awaiting phase, i don't know what to do(**
. "<input type='submit' name='submit'/>";
echo "</form>";
}
else { ?>
<form action="TEST ZONE.php" method="post">
<h3>Register Form </h3>
<label for="title">Title </label>
<select name="title">
<option name="mr">Mr</option>
<option name="ms">Ms</option>
</select><br><br><br>
<label for="fName">First Name</label><br>
<input type="text" name="fName" id="fName" value="<?php if (isset($fName)) { echo $fName; } ?>"><br><?php
if (isset( $errorMsg1 )) {
echo $errorMsg1;
}
?><br><br>
<label for="lName">Last Name</label><br>
<input type="text" name="lName" id="lName" value="<?php if (isset($lName)) { echo $lName; } ?>"><br><?php
if (isset( $errorMsg2 )) {
echo $errorMsg2;
}
?><br><br>
<label for="age">Age</label><br>
<input type="text" name="age" id="age" value="<?php if (isset($age)) { echo $age; }?>"><br><?php
if (isset($errorMsg3)){
echo $errorMsg3;
} ?><br><br>
<input type="submit" value="Submit"><input type="reset">
</form> <?php } ?>
</div>
</body>
</html>
Add action in your form to redirect final page.
You already have all values in session so you can access it in final page also
<?php
// the php code
session_start();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// setting up the variables
$title = $_POST['title'];
$fName = trim(filter_input(INPUT_POST,'fName', FILTER_SANITIZE_STRING));
$lName = trim(filter_input(INPUT_POST,'lName',FILTER_SANITIZE_STRING));
$age = intval($_POST['age']);
$_SESSION['title'] = $title;
$_SESSION['fName'] = $fName;
$_SESSION['lName'] = $lName;
$_SESSION['age'] = $age;
//checking for possible errors
if ( $fName == "" || strlen($fName) <= 2 ) {
$errorMsg1 = "<span>Provide your First name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $lName == "" || strlen($lName) <= 2 ) {
$errorMsg2 = "<span>Provide your Last name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $age < 18 ) {
$errorMsg3 = "<span>You must be 18 or above!</span>";
$status = false;
}
else { $status = true; }
// redirecting to done page
if ($status) {
header("Location:TEST ZONE.php?status=awaiting");
}
}
?>
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<div id="wrapper">
<?php
if ( isset($_GET['status']) && $_GET['status'] == "awaiting" ) {
echo "<form action='final_page.php'>"
. "Check your Details!<br>"
. $_SESSION['title'] . "<br>"
. $_SESSION['fName'] . "<br>"
. $_SESSION['lName'] . "<br>"
. $_SESSION['age'] . "<br>"
// **NOW WHEN I'M in the awaiting phase, i don't know what to do(**
. "<input type='submit' name='submit'/>";
echo "</form>";
}
else { ?>
<form action="TEST ZONE.php" method="post">
<h3>Register Form </h3>
<label for="title">Title </label>
<select name="title">
<option name="mr">Mr</option>
<option name="ms">Ms</option>
</select><br><br><br>
<label for="fName">First Name</label><br>
<input type="text" name="fName" id="fName" value="<?php if (isset($fName)) { echo $fName; } ?>"><br><?php
if (isset( $errorMsg1 )) {
echo $errorMsg1;
}
?><br><br>
<label for="lName">Last Name</label><br>
<input type="text" name="lName" id="lName" value="<?php if (isset($lName)) { echo $lName; } ?>"><br><?php
if (isset( $errorMsg2 )) {
echo $errorMsg2;
}
?><br><br>
<label for="age">Age</label><br>
<input type="text" name="age" id="age" value="<?php if (isset($age)) { echo $age; }?>"><br><?php
if (isset($errorMsg3)){
echo $errorMsg3;
} ?><br><br>
<input type="submit" value="Submit"><input type="reset">
</form> <?php } ?>
</div>
final_page.php
<?php
session_start();
$title = $_SESSION['title'];
$fName = $_SESSION['fName'];
$lName = $_SESSION['lName'];
$age = $_SESSION['age'];
?>
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
EDIT/UPDATE:
I moved my php code from my process.php file to the top of my contact.php file and it worked. So what am I missing from the process.php file that is not redirecting it back to the contact.php page?
This is my html in contact.php
<?php echo $message; ?>
<form action="process.php" method="post" name="sign_up">
<input type="text" name="first_name" placeholder="First Name" value="<?php echo $_POST[first_name]; ?>" required/>
<input type="text" name="last_name" placeholder="Last Name" value="<?php echo $_POST[last_name]; ?>" required/><br>
<label class="bill-address">Billing Address:<br>
<input type="text" name="address1" placeholder="Address 1" value="<?php echo $_POST[address1]; ?>" required/><br>
<input type="text" name="address2" placeholder="Address 2" value="<?php echo $_POST[address2]; ?>" /><br>
<input type="text" name="city" placeholder="City" value="<?php echo $_POST[city]; ?>" required/>
</label>
<?php
$state_list = array('AL'=>"Alabama",
'AK'=>"Alaska",
'AZ'=>"Arizona",
'AR'=>"Arkansas",
'WV'=>"West Virginia",
'WI'=>"Wisconsin",
'WY'=>"Wyoming");
?>
<select name="state">
<?php
while(list($k,$v) = each($state_list)) {
$selected = '';
if ($k == $_POST[state]) {
$selected = ' selected="true"';
}
echo "<option value=\"$k\"$selected>$v</option>\n";
}
?>
</select>
<input type="text" name="zip" placeholder="Zip Code" value="<?php echo $_POST[zip]; ?>" required/>
<br style="clear: left;" />
<input type="email" name="email" placeholder="you#youremail.com" value="<?php echo $_POST[email]; ?>" required/>
<input type="tel" name="phone" placeholder="Phone" value="<?php echo $_POST[phone]; ?>" required/>
<h3>Choose your Package</h3>
<select name="package">
<option value="Free">Free!</option>
<option value="Basic">Basic</option>
<option value="Corporate">Corporate</option>
<option value="Enterprise">Enterprise</option>
<option value="Enterprise_20">Enterprise 20</option>
<option value="Enterprise_50">Enterprise 50</option>
<option value="Enterprise_100">Enterprise 100</option>
</select>
<h3>Add Media Package?</h3>
<input type="radio" name="Yes" value="yes" />Yes
<input type="radio" name="No" value="no" />No
<button type="submit" class="btn">Send »</button>
<?php echo $success_message; ?>
</form>
And this is my process.php
//validate email
function is_valid_email($email) {
$result = true;
$pattern = '/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\#([a-z0-9])(([a-z0-9-])*([a-z0-9]))+(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i';
if(!preg_match($pattern, $email)) {
$result = false;
}
return $result;
}
//when submit has been pressed, begin form validate
if(isset($_POST['submit'])) {
$valid = true;
$message = '';
if ( $_POST['first_name'] == "" ) {
$message .= "Please include your first name. ";
$valid = false;
}
if ( $_POST['last_name'] == "" ) {
$message .= "Please include your last name. ";
$valid = false;
}
if ( $_POST['address1'] == "" ) {
$message .= "Please include your billing address. ";
$valid = false;
}
if ( $_POST['city'] == "" ) {
$message .= "Please enter a city. ";
$valid = false;
}
if ( $_POST['state'] == "" ) {
$message .= "Please select a state. ";
$valid = false;
}
if ( $_POST['zip'] == "" ) {
$message .= "Please include a zip code. ";
$valid = false;
}
if ( $_POST['phone'] == "" ) {
$message .= "Please include your phone number. ";
$valid = false;
}
if ( !is_valid_email($_POST['email']) ) {
$message .= "A valid email is required. ";
$valid = false;
}
if ( $_POST['package'] == "" ) {
$message .= "You forgot to select a service package. ";
$valid = false;
}
if ( $valid == true ) {
$success_message = 'Brilliant I say! We will be in contact with you shortly.';
//clear form when submission is successful
unset($_POST);
}
}
It is not working. Also the html5 validation isn't even working either. Is there something wrong with my form markup?
When you click on submit, your browser navigates to process.php. All of the code from contact.php is forgotten and a new page is generated.
There is no implied link between the two pages. The messages from process.php will not apppear on contact.php. Currently, process.php doesn't echo anything, so you're probably arriving at a blank page.
An alternate way to do this would be to merge the two pages like this:
<?php
//validate email
function is_valid_email($email) {
$result = true;
$pattern = '/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\#([a-z0-9])(([a-z0-9-])*([a-z0-9]))+(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i';
if(!preg_match($pattern, $email)) {
$result = false;
}
return $result;
}
//when submit has been pressed, begin form validate
if(isset($_POST['submit'])) {
$valid = true;
$message = '';
if ( $_POST['first_name'] == "" ) {
$message .= "Please include your first name. ";
$valid = false;
}
if ( $_POST['last_name'] == "" ) {
$message .= "Please include your last name. ";
$valid = false;
}
if ( $_POST['address1'] == "" ) {
$message .= "Please include your billing address. ";
$valid = false;
}
if ( $_POST['city'] == "" ) {
$message .= "Please enter a city. ";
$valid = false;
}
if ( $_POST['state'] == "" ) {
$message .= "Please select a state. ";
$valid = false;
}
if ( $_POST['zip'] == "" ) {
$message .= "Please include a zip code. ";
$valid = false;
}
if ( $_POST['phone'] == "" ) {
$message .= "Please include your phone number. ";
$valid = false;
}
if ( !is_valid_email($_POST['email']) ) {
$message .= "A valid email is required. ";
$valid = false;
}
if ( $_POST['package'] == "" ) {
$message .= "You forgot to select a service package. ";
$valid = false;
}
if ( $valid == true ) {
$success_message = 'Brilliant I say! We will be in contact with you shortly.';
//clear form when submission is successful
//don't clear this, you need this to re-populate the page below
//unset($_POST);
}
}
?><!doctype html>
<html>
<head>
...
</head>
<body>
<?php echo $message; ?>
<form action="contact.php" method="post" name="sign_up">
<input type="text" name="first_name" placeholder="First Name" value="<?php echo $_POST[first_name]; ?>" required/>
<input type="text" name="last_name" placeholder="Last Name" value="<?php echo $_POST[last_name]; ?>" required/><br>
<label class="bill-address">Billing Address:<br>
<input type="text" name="address1" placeholder="Address 1" value="<?php echo $_POST[address1]; ?>" required/><br>
<input type="text" name="address2" placeholder="Address 2" value="<?php echo $_POST[address2]; ?>" /><br>
<input type="text" name="city" placeholder="City" value="<?php echo $_POST[city]; ?>" required/>
</label>
<?php
$state_list = array('AL'=>"Alabama",
'AK'=>"Alaska",
'AZ'=>"Arizona",
'AR'=>"Arkansas",
'WV'=>"West Virginia",
'WI'=>"Wisconsin",
'WY'=>"Wyoming");
?>
<select name="state">
<?php
while(list($k,$v) = each($state_list)) {
$selected = '';
if ($k == $_POST[state]) {
$selected = ' selected="true"';
}
echo "<option value=\"$k\"$selected>$v</option>\n";
}
?>
</select>
<input type="text" name="zip" placeholder="Zip Code" value="<?php echo $_POST[zip]; ?>" required/>
<br style="clear: left;" />
<input type="email" name="email" placeholder="you#youremail.com" value="<?php echo $_POST[email]; ?>" required/>
<input type="tel" name="phone" placeholder="Phone" value="<?php echo $_POST[phone]; ?>" required/>
<h3>Choose your Package</h3>
<select name="package">
<option value="Free">Free!</option>
<option value="Basic">Basic</option>
<option value="Corporate">Corporate</option>
<option value="Enterprise">Enterprise</option>
<option value="Enterprise_20">Enterprise 20</option>
<option value="Enterprise_50">Enterprise 50</option>
<option value="Enterprise_100">Enterprise 100</option>
</select>
<h3>Add Media Package?</h3>
<input type="radio" name="Yes" value="yes" />Yes
<input type="radio" name="No" value="no" />No
<button type="submit" class="btn">Send »</button>
<?php echo $success_message; ?>
</form>
</body>
</html>
The $message and $success_message variables are now saved and they should display in the page markup below.
//validate email
function is_valid_email($email) {
$result = true;
$pattern = '/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\#([a-z0-9])(([a-z0-9-])*([a-z0-9]))+(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i';
if(!preg_match($pattern, $email)) {
$result = false;
}
return $result;
}
//when submit has been pressed, begin form validate
if(isset($_POST['submit'])) {
$valid = true;
$message = '';
if ( $_POST['first_name'] == "" ) {
$message = "Please include your first name. ";
echo $message;
$valid = false;
}
if ( $_POST['last_name'] == "" ) {
$message = "Please include your last name. ";
echo $message;
$valid = false;
}
if ( $_POST['address1'] == "" ) {
$message = "Please include your billing address. ";
echo $message;
$valid = false;
}
if ( $_POST['city'] == "" ) {
$message = "Please enter a city. ";
echo $message;
$valid = false;
}
if ( $_POST['state'] == "" ) {
$message = "Please select a state. ";
echo $message;
$valid = false;
}
if ( $_POST['zip'] == "" ) {
$message = "Please include a zip code. ";
echo $message;
$valid = false;
}
if ( $_POST['phone'] == "" ) {
$message = "Please include your phone number. ";<
echo $message;
$valid = false;
}
if ( !is_valid_email($_POST['email']) ) {
$message = "A valid email is required. ";
echo $message;
$valid = false;
}
if ( $_POST['package'] == "" ) {
$message = "You forgot to select a service package. ";
echo $message;
$valid = false;
}
if ( $valid == true ) {
$success_message = 'Brilliant I say! We will be in contact with you shortly.';
echo $success_message;
//clear form when submission is successful
unset($_POST);
}
}
i added echo $message for echoing during validation and .= was i think wrong way, otherwise you would have a message that contains all error messages..
Try adding this after the unset( $_POST ) line:
header('Location: contact.php');
That should take you back to the contact.php page.
EDIT:
However, in order for your code completely to work the way you want it, here what I would do.
<?php
session_start();
if (isset ($_SESSION['message'])) {
echo $_SESSION['message'];
session_destroy();
}
?>
<form action="process.php" method="post" name="sign_up">
<input type="text" name="first_name" placeholder="First Name" value="<?php echo $_POST[first_name]; ?>" />
<input type="text" name="last_name" placeholder="Last Name" value="<?php echo $_POST[last_name]; ?>" /><br>
<label class="bill-address">Billing Address:<br>
<input type="text" name="address1" placeholder="Address 1" value="<?php echo $_POST[address1]; ?>" /><br>
<input type="text" name="address2" placeholder="Address 2" value="<?php echo $_POST[address2]; ?>" /><br>
<input type="text" name="city" placeholder="City" value="<?php echo $_POST[city]; ?>" />
</label>
<?php
$state_list = array('AL'=>"Alabama",
'AK'=>"Alaska",
'AZ'=>"Arizona",
'AR'=>"Arkansas",
'WV'=>"West Virginia",
'WI'=>"Wisconsin",
'WY'=>"Wyoming");
?>
<select name="state">
<?php
while(list($k,$v) = each($state_list)) {
$selected = '';
if ($k == $_POST[state]) {
$selected = ' selected="true"';
}
echo "<option value=\"$k\"$selected>$v</option>\n";
}
?>
</select>
<input type="text" name="zip" placeholder="Zip Code" value="<?php echo $_POST[zip]; ?>" />
<br style="clear: left;" />
<input type="email" name="email" placeholder="you#youremail.com" value="<?php echo $_POST[email]; ?>" />
<input type="tel" name="phone" placeholder="Phone" value="<?php echo $_POST[phone]; ?>" />
<h3>Choose your Package</h3>
<select name="package">
<option value="Free">Free!</option>
<option value="Basic">Basic</option>
<option value="Corporate">Corporate</option>
<option value="Enterprise">Enterprise</option>
<option value="Enterprise_20">Enterprise 20</option>
<option value="Enterprise_50">Enterprise 50</option>
<option value="Enterprise_100">Enterprise 100</option>
</select>
<h3>Add Media Package?</h3>
<input type="radio" name="Yes" value="yes" />Yes
<input type="radio" name="No" value="no" />No
<button type="submit" class="btn">Send »</button>
<?php
//session already started on line 2
if (isset( $_SESSION['success'] )) {
echo $_SESSION['success'];
session_destroy();
}
?>
</form>
That's for contact.php, and
<?php
//when submit has been pressed, begin form validate else return to contact.php
if ( $_SERVER[ 'REQUEST_METHOD' ] == "POST" ) {
session_start();
//validate email
function is_valid_email($email) {
$result = true;
$pattern = '/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\#([a-z0-9])(([a-z0-9-])*([a-z0-9]))+(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i';
if(!preg_match($pattern, $email)) {
$result = false;
}
return $result;
}
$valid = true;
$message = '';
if ( $_POST['first_name'] == "" ) {
$message .= "Please include your first name. ";
$valid = false;
}
if ( $_POST['last_name'] == "" ) {
$message .= "Please include your last name. ";
$valid = false;
}
if ( $_POST['address1'] == "" ) {
$message .= "Please include your billing address. ";
$valid = false;
}
if ( $_POST['city'] == "" ) {
$message .= "Please enter a city. ";
$valid = false;
}
if ( $_POST['state'] == "" ) {
$message .= "Please select a state. ";
$valid = false;
}
if ( $_POST['zip'] == "" ) {
$message .= "Please include a zip code. ";
$valid = false;
}
if ( $_POST['phone'] == "" ) {
$message .= "Please include your phone number. ";
$valid = false;
}
if ( !is_valid_email($_POST['email']) ) {
$message .= "A valid email is required. ";
$valid = false;
}
if ( $_POST['package'] == "" ) {
$message .= "You forgot to select a service package. ";
$valid = false;
}
if ( $valid == true ) {
$success_message = 'Brilliant I say! We will be in contact with you shortly.';
//clear form when submission is successful
unset($_POST);
$_SESSION['success']=$success_message;
}
else {
$_SESSION['message'] = $message;
}
header('Location: contact.php');
} // end of if ( $_SERVER[ 'REQUEST_METHOD' ] == "POST" )
else header('Location: contact.php');
?>
process.php
The following control I think was creating the biggest confusion in your code:
//when submit has been pressed, begin form validate
if(isset($_POST['submit']))
as soon as I replaced it, everything started to work better.