Link to home
Start Free TrialLog in
Avatar of Jazzy 1012
Jazzy 1012

asked on

A form to still have contents even if some are wrong

<form class="form-horizontal" action="add.php" method="post">
                <fieldset>
                    <legend>SIGN UP! <i class="fa fa-pencil pull-right"></i></legend>
 <div class="form-group">
                              
<?php 
if($_GET['a'] == 1)
{
echo "<p class='alert alert-danger'>Username Already taken</p>";

}
if($_GET['a'] == 2)
{
	echo " <p class= 'alert alert-success'> Your registration is complete </p>";
}
if($_GET['a'] == 3)
{
	echo " <p class= 'alert alert-warning'> Your email does not match </p>";
}


?> 
	<div class="col-sm-6">
        <input type="text" id="firstName" placeholder="First Name" class="form-control" name="firstname" autofocus required>
    </div>
    <div class="col-sm-6">
        <input type="text" id="lastname" placeholder="Last Name" class="form-control" name="lastname" autofocus required>
	</div>
</div>
                
                <div class="form-group">
                    <div class="col-sm-12">
                        <input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
                    </div>
                </div>
              <div class="form-group">
                    <div class="col-sm-12">
                        <input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
                    </div>
                </div>
                
                 <div class="form-group">
                    <div class="col-sm-12">
                        <input type="text" id="username" placeholder=" Username" name="username" class="form-control" required>
                    </div>
                </div>
                
                <div class="form-group">
                    <div class="col-sm-12">
                        <input type="password" id="password" placeholder="Password" name="password" class="form-control" required>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-12">
                        <input type="text" id="datepicker" placeholder= "DOB" name="birthday" class="form-control" required>
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-1"></label>
                    <div class="col-sm-8">
                        <div class="row">
                            
                                <label class="radio-inline">
                                    <input type="radio" id="radio" value="Female" name= "gender" required>Female
                                </label>
                            
                           
                                <label class="radio-inline">
                                    <input type="radio" id="radio" value="Male" name= "gender">Male
                                </label>
                            
                        </div>
                    </div>
                </div> <!-- /.form-group -->
                <div class="form-group">
                    <div class="col-sm-4 col-sm-offset-3">
                        <button type="submit" class="btn btn-primary btn-block">Register</button>
                    </div>
                </div>
            </form>

Open in new window


I have this form that you register in and as you can see it processes in login.php and then it tells you if your registration is complete, or if username already taken or if email doesn't match. Is there a way that if it wants to output "username already taken" or "emails don't match" for the other information to stay? because now when that occurs they have to input there information all over again
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

since you are making the form posting to add.php and if there's anything that prevent the registration of the account, you probably need to set store fields into session variables, so that it can be retrieved back and display in the form accordingly.

IF the form is posting back to itself, you probably can look for $_POST['yourfieldname'] instead, since your form's method is POST.

but both approaches need your page to be in .php
Avatar of Jazzy 1012
Jazzy 1012

ASKER

here is my "Add.php" what do else do I need to have?
if ($_POST['firstname'] != "" && $_POST['lastname'] !="" && $_POST['email'] != "" && $_POST['cemail'] !="" && $_POST['username'] !="" && $_POST['password'] !="" && $_POST['birthday'] !="" && $_POST['gender'] !="")
{
	$firstname = $_POST['firstname'];
	$lastname = $_POST['lastname'];
	$email = $_POST['email'];
	$cemail = $_POST['cemail'];
	$password = $_POST['password'];
	$birthday = $_POST['birthday'];
	$gender = $_POST['gender'];
	$username = $_POST['username'];
	$file = 'default.png';
	
	$query1="SELECT * FROM users WHERE username = '$username' ";
	$username = mysqli_real_escape_string($conn,$username);
	$password = mysqli_real_escape_string($conn,$password);
	$firstname = mysqli_real_escape_string($conn,$firstname);
	$lastname = mysqli_real_escape_string($conn,$lastname);
	$email = mysqli_real_escape_string($conn,$email);
	$cemail = mysqli_real_escape_string($conn,$cemail);
	$birthday = mysqli_real_escape_string($conn,$birthday);
	$gender = mysqli_real_escape_string($conn,$gender);
	
	
	
	if($email != $cemail)
	{
		
	header("Location: index.php/?a=3");
	die();
	}

	$result = mysqli_query($conn,$query1)
	or die(mysqli_error($conn));  

	if(mysqli_num_rows($result) != 0)
	{
		header("Location: index.php/?a=1");
	}
	
	
	
	else {
	$query = "INSERT INTO users (firstname, lastname, email, password, date_birth, gender, username, file) VALUES ('$firstname','$lastname','$email','$password', '$birthday' , '$gender' , '$username', '$file')";
	
	
	$data = mysqli_query($conn,$query)or die(mysqli_error($conn));
	
	header("Location: index.php/?a=2");
	  
	}
	
}

Open in new window

This script shows the general design.  
<?php // demo/form_highlight_errors.php
/**
 * Demonstrate how to highlight errors in form input, and remember valid inputs
 * Client is asked to put in a value
 * If the value fails our test we show an error message
 * We put a marker next to the input control on the form
 * We turn the form border red
 * SEE http://www.w3schools.com/CSS/pr_class_visibility.asp
 */
error_reporting(E_ALL);


// THESE STYLE ELEMENTS ARE SET FOR THE SCRIPT INITIALIZATION
$error_abc = $error_xyz = $error_any = 'hidden';
$boxer_abc = $boxer_xyz              = 'black';


// CAPTURE AND NORMALIZE THE POST VARIABLES - ADD YOUR OWN SANITY CHECKS HERE
$abc = (isset($_POST["abc"])) ? trim(strtoupper($_POST["abc"])) : NULL;
$xyz = (isset($_POST["xyz"])) ? trim(strtoupper($_POST["xyz"])) : NULL;


// IF ANYTHING WAS POSTED, VALIDATE IT
if (!empty($_POST))
{
    // VALIDATE THE 'abc' FIELD
    if ($abc != 'ABC')
    {
        // VALIDATION FAILED
        $error_abc = $error_any = 'visible';
        $boxer_abc = 'red';

        // BECAUSE THIS FAILED VALIDATION, REMOVE IT FROM THE FORM
        $abc       = NULL;
    }

    // VALIDATE THE 'xyz' FIELD
    if ($xyz != 'XYZ')
    {
        // VALIDATION FAILED
        $error_xyz = $error_any = 'visible';
        $boxer_xyz = 'red';

        // BECAUSE THIS FAILED VALIDATION, REMOVE IT FROM THE FORM
        $xyz       = NULL;
    }

    // DO WE HAVE INPUT FREE FROM ANY ERRORS?
    if ($error_any != 'visible')
    {
        echo "CONGRATULATIONS";
        die();
    }

    // OTHERWISE... OOPS - WE HAVE ERRORS AND MUST SHOW THE FORM AGAIN
}

// IF NOTHING WAS POSTED, OR IF THERE ARE ERRORS, WE NEED NEW CLIENT INPUT
$form = <<<ENDFORM
<style type="text/css" media="all">
.error_any { visibility:$error_any; }
.error_abc { visibility:$error_abc; }
.error_xyz { visibility:$error_xyz; }
</style>
<pre>
<form method="post">
<span class="error_any">PLEASE CORRECT THE FOLLOWING ERRORS</span>
<span class="error_abc">YOU MUST ENTER 'abc' IN THIS FIELD</span>
PLEASE ENTER "ABC" HERE: <input style="border-color:$boxer_abc;" name="abc" value="$abc" />
<span class="error_xyz">YOU MUST ENTER 'xyz' IN THIS FIELD</span>
PLEASE ENTER "XYZ" HERE: <input style="border-color:$boxer_xyz;" name="xyz" value="$xyz" />
<input type="submit" />
</form>
ENDFORM;

// WRITE THE FORM WITH THE APPROPRIATE CSS STYLES ON THE ERROR MESSAGE FIELDS
echo $form;

Open in new window

Do I put this on my index.php page?
No, it's not "replacement code."  It's a teaching example, meant to illustrate the principles.  The form remembers all the "good" inputs and forgets only the "bad" inputs.  When an input is not considered valid, an error message appears, and the input control is highlighted.  You can test it on my server, or just install it on your server to experiment with it and see its behavior.
https://iconoun.com/demo/form_highlight_errors.php
ASKER CERTIFIED SOLUTION
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Not all solutions posted here at E-E have been checked for functionality or security.  Please do not use unescaped variables in SQL query strings.  In the example above, these instructions, executed in this order, are dangerous.
// THIS DOES NOTHING BUT COPY DATA FROM ONE VARIABLE TO ANOTHER
$username = $_POST['username'];

// THIS INSTRUCTION PUTS THE COPIED AND UNFILTERED EXTERNAL DATA INTO THE QUERY STRING
// LATER THIS CAUSES THE SCRIPT TO USE THE TAINTED DATA IN A QUERY - DANGEROUS!
$query1="SELECT * FROM users WHERE username = '$username' ";

// THIS INSTRUCTION IS OUT OF PLACE - IT DOES NO GOOD TO ESCAPE THE DATA HERE
// THE UNESCAPED DATA WENT INTO THE QUERY STRING.  
$username = mysqli_real_escape_string($conn,$username);

Open in new window

How can I do session for the gender, female and male when they already have there own values?
There are multiple concepts here.  First your actual question, " Is there a way that if it wants to output "username already taken" or "emails don't match" for the other information to stay? " and another having to do with protecting your database. Ray does bring up a good point and if you are interested, that would be subject for another question.

For the actual question though, I would do this in a different manner altogether.

When you have a form where you are asking people to enter in a username, I would use an ajax request to poll your database.  Then the return of the ajax request can either create a pop up modal or just turn that field red with a note that the username is taken. Perhaps even suggest a similar username.

For "emails don't match" and other validation, I would do this client side and there are many validation plug ins for jquery out there. However, I would also always validate server side.  If something slips by my client side validation, then in my return post, I will set a server side array with validation messages and then my form can process those messages. This way you don't have to worry about sessions/cookies.

A different approach, if you want to purse this or the type of security that Ray is talking about, create a new question thread and we can  help you from there.
@Jasmine: Do you really want a user called Bobby Users?