Forum Moderators: coopster

Message Too Old, No Replies

Help Form Validation / General

Validation Forms with PHP

         

CyberRoyal

12:28 pm on Apr 10, 2009 (gmt 0)

10+ Year Member



Afternoon All,

I am currently writing a registration script but I just cant get it to behave the way I want it to. Basically what Im after is a form the will allow a user to register for a website. The form will have validation to ensure that all data has been entered and that certain data matches (password and e-mail details).

If the data is not completed or does not match I would like the form to reload the page with an overall message stating the form was not compelted correctly with the data that was submitted still visable to be amended. I dont want the user to have to keep hitting back on their browser or to keep re-entering the information each time they cock up or the username is unavailable etc, etc.

below is my code so far but I just cant seem to get it to do what I want....The script also continues to run even if all the data has not been inputted and will still write to the db (username, password etc...even if blank)

PHP code

<?php
mysql_connect("localhost", "username", "password") or die("Sorry We are unable to Connect to the Database at this time");
mysql_select_db("webvisits") or die("We are unable to locate the required table for this operation");

$message = 'Username';
$error_firstname = $_POST['firstname'];
$error_surname = $_POST['lastname'];
$error_email1 = $_POST['email'];
$error_email2 = $_POST['email2'];
$error_dob = $_POST['dob'];
$error_num = $_POST['number'];
$error_firstline = $_POST['addressFirstLine'];
$error_town = $_POST['town'];
$error_county = $_POST['county'];
$error_postcode = $_POST['postcode'];
$error_username = $_POST['username'];
$Introduction = '<p>New Users</p>
<p>Hello and thank you for registering for our online visit booking service. Please complete the following details that will be used to create your online account. Please ensure that all information is completed accuratly to ensure that your registration and account is completed without any delay.</p>
<p>Once your account has been created, a conformation e-mail will be sent to the address you have supplied below.</p>';

$checkusername = $_POST['username'];
$check = mysql_query("SELECT username FROM auth_users WHERE username = '$checkusername'");
$check2 = mysql_num_rows($check);
if ($_POST) {

if (!$_POST['username'] ¦¦ !$_POST['password'] ¦¦ !$_POST['password2'] ) {
$Introduction = 'All required information not completed or entered correctly. Please check your information and resubmit';
header ("location:newuser_test.php");
die;
}
if ($check2 != 0) {
$message = 'Username taken. Please try another';
}
else {
$_POST['password'] = md5($_POST['password']);
if (!get_magic_quotes_gpc()) {
$_POST['password'] = addslashes($_POST['password']);
$_POST['username'] = addslashes($_POST['username']);
}
$insert = "INSERT INTO auth_users (username, password)
VALUES ('".$_POST['username']."', ".$_POST['password']."')";

$add_member = mysql_query($insert)
or die (mysql_error());

$insertdetail ="INSERT INTO users_detail (username, first_name, last_name, email, dob, number, first_line, town, county, postcode)
VALUES ('".$_POST['username']."', '".$_POST['firstname']."', '".$_POST['lastname']."', '".$_POST['email']."', '".$_POST['dob']."', '".$_POST['number']."', '".$_POST['addressFirstLine']."', '".$_POST['town']."', '".$_POST['county']."', '".$_POST['postcode']."')";

$add_member = mysql_query($insertdetail)
or die ("detail query");

If ($add_member) {header( "Location:loginform.html");}
}
}
?>

HTML

<?php echo $Introduction; ?>

<form id="newuser" name="newuser" method="post" action="newuser_test.php">
<p>
<label>First Name
<input name="firstname" type="text" value="<?php echo $error_firstname; ?>" id="firstname" tabindex="1" />
<br />
<br />
Last Name
<input type="text" name="lastname" value="<?php echo $error_surname; ?>" id="lastname" tabindex="2" />
</label>
</p>
<p>
<label>Email address
<input type="text" name="email" value="<?php echo $error_email1; ?>" id="email" tabindex="3" />
</label>
</p>
<p>
<label>Confirm Email address
<input type="text" name="email2" value="<?php echo $error_email2; ?>" id="email2" tabindex="4" />
</label>
</p>
<p>
<label>Date of Birth
<input type="text" name="dob" value="<?php echo $error_dob; ?>" id="dob" tabindex="5" />
</label>
</p>
<p>
<label>House Number
<input type="text" name="number" value="<?php echo $error_num; ?>" id="number" tabindex="6" />
</label>
</p>
<p>
<label>First line of address
<input type="text" name="addressFirstLine" value="<?php echo $error_firstline; ?>" id="addressFirstLine" tabindex="7" />
</label>
</p>
<p>
<label>Town
<input type="text" name="town" value="<?php echo $error_town; ?>" id="town" tabindex="8" />
</label>
</p>
<p>
<label>County
<input type="text" name="county" value="<?php echo $error_county; ?>" id="county" tabindex="9" />
</label>
</p>
<p>
<label>Postcode
<input type="text" name="postcode" value="<?php echo $error_postcode; ?>" id="postcode" tabindex="10" />
</label>
</p>
<p>
<label><?php /*this displays the result of the $message variable*/ echo $message; ?>
<input type="text" name="username" value="<?php echo $error_username; ?>" id="username" tabindex="11" />
</label>
</p>
<p>
<label>Passsword
<input type="text" name="password" id="password" tabindex="12"/>
</label>
</p>
<p>
<label>Confirm Password
<input type="text" name="password2" id="password2" tabindex="13"/>
</label>
</p>
<p>
<label>
<input type="submit" name="submit" id="submit" value="Submit" />
</label>
</p>
</form>

If you need anything else posting please let me know but I have been on this all morning and im just not getting anywhere.

Many thanks

rocknbil

4:25 pm on Apr 10, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



First, look at the overall program logic:

<?php

- db connect
- set variables for use in form
- check for user name

if ($_POST) {

if (user/pass is blank) { // (note second suggestion, this is probably the error)
die/redirect if error
}

if ($check2 != 0) {
compile a message if user name exists
}
else {
- clean username/pass
}

- perform an insert, unrestricted by any of the above conditions

if ($add_member) { go to login }

} # End if $_POST

} # what's this, is this an extra bracket, a syntax error? Looks like it.

- output html form.

What I'm seeing (and not seeing, if the last bracket is not an error) is input data that, if errant, redirects, when you have the form already inline. Things are also occurring at odd places and may provide confusing output; note how the insert gets performed whether or not there are errant conditions (which may not be detected as you expect, see below)

I would try to organize this more like this:


$errorList = $form = '';
- initialize variables for use in form
if ($_POST) {
- db connect
- set variables for use in form to what's in $_POST
- Check for required fields (which you may have wrong, see below.)
if not present, add message to error list: $errorList .= '<li>message here</li>';
- check for existing user name
- If user name exists, add message to $errorList
if ($errorList == '') {
-- do the database inserts
-- redrect to login form - OR output it RIGHT HERE and EXIT
}
}
// Whether or not you have post, if it doesn't exit to login,
// you will want the form to output
if ($errorList != '') {
echo "<p style="red bold">ERRORS:</p><ul>" . $errorList . "</ul>";
}
else { output your normal intro; }
- output the form with fields intact (or not.)

This is a more structured approach: initialize variables, check data, if errant compile error message, return to form; if all is well, enter into database, output login form; on first call none of this happens, output form with welcome message.

I think your immediate problem most likely lies here:

if (!$_POST['username'] ¦¦ !$_POST['password'] ¦¦ !$_POST['password2'] ) {
$Introduction = 'All required information not completed or entered correctly. Please check your information and resubmit';
header ("location:newuser_test.php");
die;
}

First, I'm guessing the text/password fields are likely present, they are just a blank string. Checkboxes will only be in post if they are checked, but text inputs, text areas, and select will be present, but often as a blank string. So try

if (($_POST['username']=='') or ($_POST['password']=='') or ($_POST['password2']=='')) {

You could be a little more specific if you want, for say, text only user names and a password that must contain numbers and letters:

if (preg_match("/^[^\w]+$/",$_POST['username']) or preg_match("/^[^\w\d]+$/",$_POST['password']) or preg_match("/^[^\w\d]+$/",$_POST['password'])) {
$errList .= '<li>User name must be all letters, password letters and numbers only</li>';

A caveat, you will get warnings if you index these and they are not set, so you might want to do


if (isset($_POST['username']) and isset($_POST['password']) and isset ($_POST['password2'])) {
if (preg_match("/^[^\w]+$/",$_POST['username']) or preg_match("/^[^\w\d]+$/",$_POST['password']) or
preg_match("/^[^\w\d]+$/",$_POST['password'])) {
$errList .= '<li>User name must be all letters, password letters and numbers only</li>';
}
}

Second, note my comments on the redirect and exit on success, and how I suggest to manage that. You already have the user name variables in hand, rather than redirecting to a login page, why not just output the login form right here in this script? This doesn't affect your login script in any way, you will still need the form in it for direct requests. But if you do it here, you can load the form with the user name populated.

Or better yet, set login variables/cookies whatever and auto-log them in the first time.

CyberRoyal

5:30 pm on Apr 10, 2009 (gmt 0)

10+ Year Member



wow rocknbil,

Lots to have a look over there, appriciated. I will post how I get on.

Thanks again

CyberRoyal

6:37 pm on Apr 10, 2009 (gmt 0)

10+ Year Member



Ok rocknbil,

Am I understanding you correctly:

*1st if anything has been posted then connect to the db

if ($_POST) {
mysql_connect("localhost", "username", "password") or die("Sorry We are unable to Connect to the Database at this time");
mysql_select_db("webvisits") or die("We are unable to locate the required table for this operation");
}

//check for username and password conditions

if (isset($_POST['username']) and isset($_POST['password']) and isset ($_POST['password2'])) {
if (preg_match("/^[^\w]+$/",$_POST['username']) or preg_match("/^[^\w\d]+$/",$_POST['password']) or
preg_match("/^[^\w\d]+$/",$_POST['password'])) {
$errList .= '<li>User name must be all letters, password letters and numbers only</li>';

//check to see if username has already been allocated
$checkusername = $_POST['username'];
$check = mysql_query("SELECT username FROM auth_users WHERE username = '$checkusername'");
$check2 = mysql_num_rows($check);
if ($check2 != 0) {
$errList .= '<li>Username taken. Please try another<li>';

//if the errList is empty insert data into the db

if ($errorList == '') {
$insert = "INSERT INTO auth_users (username, password)
VALUES ('".$_POST['username']."', '".$_POST['password']."')";

$add_member = mysql_query($insert)
or die (mysql_error());

$insertdetail ="INSERT INTO users_detail (username, first_name, last_name, email, dob, number, first_line, town, county, postcode)
VALUES ('".$_POST['username']."', '".$_POST['firstname']."', '".$_POST['lastname']."', '".$_POST['email']."', '".$_POST['dob']."',
'".$_POST['number']."', '".$_POST['addressFirstLine']."', '".$_POST['town']."', '".$_POST['county']."', '".$_POST['postcode']."')";

$add_member = mysql_query($insertdetail)
or die ("detail query");

then the HTML section

rocknbil

1:52 am on Apr 11, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Not quite,

if ($_POST) {
mysql_connect("localhost", "username", "password") or die("Sorry We are unable to Connect to the Database at this time");
mysql_select_db("webvisits") or die("We are unable to locate the required table for this operation");
} <------------------

Your "if" closes too early.

The idea is to wrap all the heavy lifting in that "if".

if $_POST {
--- do stuff that relies on post, including error checks, database insert, generate login on success, etc.
}

--- If you have a successful registration you will never get to this point in the program because you've output the login page already (or redirected) in the if above. The only reason you're here is that there are no post variables or there is an ERROR.

--- If the stuff in post creates errors, display them here

-- Display the form here, if post isn't present it won't connect tothe database (economy) or do any error checking, errList will be blank . . . this will just display the form. If post is present and it errors, it will also display the form, but with the errors above it.

Also, WATCH FOR TYPOS:

$errList .= '<li>Username taken. Please try another<li>';
//if the errList is empty insert data into the db
if ($errorList == '') {

At this point $errorList is undefined/not set, so it does not equal an empty string. Little stuff like that will drive you bonkers. :-)

On that point, be SURE to set $errList=''; at the top of your script, or change how you test for it. If you don't do that it will throw errors (program errors for undefined variables.) Alternatively, you can just not set it to blank and do "if isset($errList)" . . .

CyberRoyal

4:45 pm on Apr 11, 2009 (gmt 0)

10+ Year Member



right im getting there ( I think)

<?php

$errorList = '';

if ($_POST)
{
mysql_connect("localhost", "username", "password") or die("Sorry We are unable to Connect to the Database at this time");
mysql_select_db("webvisits") or die("We are unable to locate the required table for this operation");

$_POST['password'] = md5($_POST['password']);

if (!get_magic_quotes_gpc()) {
$_POST['password'] = addslashes($_POST['password']);
$_POST['username'] = addslashes($_POST['username']);
}
if (isset($_POST['username']) and isset($_POST['password']) and isset ($_POST['password2']))
{
if (preg_match("/^[^\w]+$/",$_POST['username']) or preg_match("/^[^\w\d]+$/",$_POST['password']) or
preg_match("/^[^\w\d]+$/",$_POST['password']))
{$errList .= '<li>User name must be all letters, password letters and numbers only</li>';
}
}

$checkusername = $_POST['username'];
$check = mysql_query("SELECT username FROM auth_users WHERE username = '$checkusername'");
$check2 = mysql_num_rows($check);

if ($check2 != 0)
{$errorList = '<li>Username taken. Please try another</li>';}

$insert = "INSERT INTO auth_users (username, password)
VALUES ('".$_POST['username']."', '".$_POST['password']."')";

$insertdetail ="INSERT INTO users_detail (username, first_name, last_name, email, dob, number, first_line, town, county, postcode)
VALUES ('".$_POST['username']."', '".$_POST['firstname']."', '".$_POST['lastname']."', '".$_POST['email']."', '".$_POST['dob']."',
'".$_POST['number']."', '".$_POST['addressFirstLine']."', '".$_POST['town']."', '".$_POST['county']."', '".$_POST['postcode']."')";

$add_member = mysql_query($insert)
or die (mysql_error());

$add_member = mysql_query($insertdetail)
or die (mysql_error());

if ($add_member)
{header( "Location:loginform.html");}

}

if ($errorList != '')
{echo "$errorList "; }

else { echo "output your normal intro"; }
?>

The problem I am having is that if the username already exists I get the message "duplicate value at 1" and the $errorList is not being displayed at all.

if I include
if (errorList =='')
{
//then the insert and redirect script
}
the form just reloads itself on submit without writing anything to the db or displaying the $errorList again.

Help...please tell me I'm getting closer.

rocknbil

3:05 pm on Apr 12, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The problem I am having is that if the username already exists I get the message "duplicate value at 1" and the $errorList is not being displayed at all.

Because you're going on to insert, regardless of what happens in $check2, and the database is probably set to unique in username. Look:

if ($check2 != 0)
{$errorList = '<li>Username taken. Please try another</li>';}
// Okay, you have a value in $errorList, so,

if ($errorList == '') {
$insert = .... only insert if no error

$add_member = .... ditto
}

if ($errorList != '')
{echo "$errorList "; }

else { echo "output your normal intro"; }
?>