Jump to content


Photo

How do I stop a form from submitting to database when there's errors?


  • Please log in to reply
16 replies to this topic

#1 simcoweb

simcoweb
  • Members
  • PipPipPip
  • Advanced Member
  • 1,102 posts
  • LocationCA

Posted 14 September 2006 - 10:34 PM

I have a registration form that's using PHP validation. The problem is even though there may be errors in the field entries by the person registering it's still submitting to the mysql database. The form displays the error messages as to which fields they messed up or forgot. But, once they correct those and resubmit then it creates duplicate entries in the database.

I need to know how to stop that. Thanks!

Here's the validation code:

// Validate users input
if(!empty($_POST))
{
	// Check email is a valid email address
	if(isset($_POST['email'])) if(!ereg("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,}\\.[0-9]{1,}\\.[0-9]{1,}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,}|[0-9]{1,})(\\]?)$", $_POST['email'])) $eg_error['email'] = "You must enter a valid email address!";
	// Check password has a value
	if(empty($_POST['password'])) $eg_error['password'] = "You must enter a password!";
	// Check that city is letters only
	if(isset($_POST['city'])) if(ereg("[0-9]", $_POST['city'])) $eg_error['city'] = "city must be letters only!";
	// Check that confirmPass is the same as (comparison)
	if(isset($_POST['confirmPass'])) if($_POST['confirmPass'] != @$_POST['password']) $eg_error['confirmPass'] = "Your passwords do not match!";
	// Check that username is numbers and letters
	if(isset($_POST['username'])) if(ereg("[!\"£\$%\^&\*()\+=\{}[.].][.[.]#~';:@/\.,<>\?\\| ]", $_POST['username'])) $eg_error['username'] = "The user name contains some illegal charactures, only use alpha-numeric charactures.";
	// Check username has a value
	if(empty($_POST['username'])) $eg_error['username'] = "You must enter a user name!";
	// Check if any errors were returned and run relevant code
	if(empty($eg_error))
	{
	}
	else
	{
	}
}


I'm assuming it needs some additional 'if' coding in the 'else' area.

#2 Wintergreen

Wintergreen
  • Members
  • PipPipPip
  • Advanced Member
  • 107 posts

Posted 14 September 2006 - 10:56 PM

Few things to clean up your code a bit.
First, you're right, you need an if, else statement. 
if(empty($_POST['form_element']) || empty($_POST['form_element2']) and so on) {
  if(empty($_POST['form_element'])
      $_SESSION['message'] .= "This part was empty<br />";
  if(empty($_POST['form_element2'])
      $_SESSION['message'] .= "This part was empty<br />";
} else {
  Do your value checking, add slashes etc
  Do your data insert here
}

The if statement makes sure there are values in the variables and then uses one variable to print out all the things that needed fixing.  The If statement checks ALL the variables from the form to see if they're empty, and if so it goes inside, thereby not touching the DB at all

#3 simcoweb

simcoweb
  • Members
  • PipPipPip
  • Advanced Member
  • 1,102 posts
  • LocationCA

Posted 14 September 2006 - 11:19 PM

Thanks for the response and tips. I'm not 100% sure I follow your suggestion so I need just a bit of clarification.

So you're saying this new code should go ahead of the validation and make the validation part of an 'else' section?

#4 Wintergreen

Wintergreen
  • Members
  • PipPipPip
  • Advanced Member
  • 107 posts

Posted 15 September 2006 - 12:07 AM

Yes, check to see that none of the form elements were empty in the IF statement, and then do your validation and database insert in the ELSE statement.  That way if anything is empty, it won't waste time validating data that is incomplete and it won't insert it into the DB. 

The $_SESSION['message'] thing is just a preference of mine.  I just add all the errors onto the end of each other and print them all in one go.  It's just easier to remember one variable. 

#5 simcoweb

simcoweb
  • Members
  • PipPipPip
  • Advanced Member
  • 1,102 posts
  • LocationCA

Posted 15 September 2006 - 04:08 AM

So do I have to name each 'form_element' or is there a global way to do it?

#6 Wintergreen

Wintergreen
  • Members
  • PipPipPip
  • Advanced Member
  • 107 posts

Posted 15 September 2006 - 04:33 AM

You name each form element so that you can check its value.  Here's an example

<form name=entry method=post action=makeentry.php>
	<table width=390 cellspacing=0 cellpadding=0>
	<tr><td>Entry Title</td></tr>
	<tr><td width=100%><input name=posttitle type=text size=45></td></tr>
	<tr><td>Entry type</td></tr>
	<tr><td><input type=radio name=posttype value=0> General Update<br />
	<input type=radio name=posttype value=3> Journal Update<br />
        <input type=radio name=posttype value=2> Art Update<br />
	</td></tr>
	<tr><td>Body</td></tr>
	<tr><td width=100%><textarea name=bodytext type=text rows=20 cols=34></textarea></td></tr>
	<tr><td><input name=submit type=submit value=submit></td></tr>
	</table>
	</form>

Then I check the values, first I see if they're empty, and if they aren't, it starts checking values and then inputs.
<? 
	session_start();

if( !empty($_POST['posttitle']) && !empty($_POST['bodytext']) && !empty($_SESSION['user_level'])) {
include 'db.php';
$posttitle = mysql_real_escape_string(strip_tags($_POST['posttitle']));
$post_body = ereg_replace("\n", "", $_POST['bodytext']);
$post_body = ereg_replace("\r", "", $post_body);
$post_body = mysql_real_escape_string(strip_tags($post_body, '<img><a>'));
$poster = $_SESSION['screenname'];
$posttype = $_POST['posttype'];
mysql_query("INSERT INTO posts (title, post_body, post_time, post_type, poster_name) VALUES('$posttitle','$post_body','$post_time','$posttype','$poster')") or die(mysql_error());
}
header("location: index.php");
exit();
?>
So as you can see, if the variables have stuff in them it goes in, does a few things and then inputs it into the DB, otherwise it skips right to the header, which sends them (in this case) to index.php

#7 simcoweb

simcoweb
  • Members
  • PipPipPip
  • Advanced Member
  • 1,102 posts
  • LocationCA

Posted 16 September 2006 - 08:16 PM

Thanks for the further code tips and info. Unfortunately this is not exactly what I need. Here's some more details:

  • I already have form field validation code that's working properly and displays the error messages if a particular field is left empty
  • The form submists the data to the database even though the input errors occur. In other words, the validation is not stopping the form from submitting the data into the database.

So, what I need is specific code that says "Even though they pressed Submit and the field validation produced an error... do not submit the data to the database. Instead, return to the form, show the error, and only enter the data IF no validation errors occur"

This is the entire section of code currently in use without errors. It performs the validation, uploads an image and inserts into the database.

// Validate users input
if(!empty($_POST))
{
	// Check email is a valid email address
	if(isset($_POST['email'])) if(!ereg("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,}\\.[0-9]{1,}\\.[0-9]{1,}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,}|[0-9]{1,})(\\]?)$", $_POST['email'])) $eg_error['email'] = "You must enter a valid email address!";
	// Check password has a value
	if(empty($_POST['password'])) $eg_error['password'] = "You must enter a password!";
	// Check that city is letters only
	if(isset($_POST['city'])) if(ereg("[0-9]", $_POST['city'])) $eg_error['city'] = "city must be letters only!";
	// Check that confirmPass is the same as (comparison)
	if(isset($_POST['confirmPass'])) if($_POST['confirmPass'] != @$_POST['password']) $eg_error['confirmPass'] = "Your passwords do not match!";
	// Check that username is numbers and letters
	if(isset($_POST['username'])) if(ereg("[!\"£\$%\^&\*()\+=\{}[.].][.[.]#~';:@/\.,<>\?\\| ]", $_POST['username'])) $eg_error['username'] = "The user name contains some illegal charactures, only use alpha-numeric charactures.";
	// Check username has a value
	if(empty($_POST['username'])) $eg_error['username'] = "You must enter a user name!";
	// Check if any errors were returned and run relevant code
	if(empty($eg_error))
	{
	}
	else
	{
	}
}

// Conditional statement
if(!empty($_POST))
{
	// Upload File
	$eg_success_File1 = false;
	if(!empty($_FILES['photo']['name']))
	{
		// Check file is not larger than specified maximum size
		$eg_allowUpload = $_FILES['photo']['size'] <= 100000 ? true : false;
		// Check file is of the specified type
		if($eg_allowUpload)
			$eg_allowUpload = preg_match('/\\.(gif|jpg|jpeg|png)$/i', $_FILES['photo']['name']) ? true : false;
		
		if($eg_allowUpload)
		{
			if(is_uploaded_file($_FILES['photo']['tmp_name']))
			{
				$eg_uploaddir = $_SERVER['DOCUMENT_ROOT']."/images/photo/";
				
				$eg_uploadFile1 = $eg_uploaddir.rawurlencode($_FILES['photo']['name']);	
				// Create a unique filename for the uploaded file
				$eg_i = 1;
				while (file_exists($eg_uploadFile1))
				{
					$eg_separated_filename = explode(".",$eg_uploadFile1);
					if (substr($eg_separated_filename[0],-1) == $eg_i)
					{
						$eg_separated_filename[0] = substr($eg_separated_filename[0], 0, (strlen($eg_separated_filename[0])-1));
						$eg_i++;
					}
					$eg_separated_filename[0] = $eg_separated_filename[0] . "$eg_i";
					$eg_uploadFile1 = implode(".",$eg_separated_filename);
				}
							
				$eg_success_File1 = move_uploaded_file($_FILES['photo']['tmp_name'], $eg_uploadFile1);
			}
			
		}
		
	}
	// Run query
	mysql_query("INSERT INTO `plateau_pros`(`username`, `password`, `confirmPass`, `firstname`, `lastname`, `email`, `business`, `title`, `address`, `city`, `zip`, `phone`, `fax`, `mobile`, `category`, `comments`, `specialties`, `photo`) VALUES('".@$_POST['username']."', '".@$_POST['password']."', '".@$_POST['confirmPass']."', '".@$_POST['firstname']."', '".@$_POST['lastname']."', '".@$_POST['email']."', '".@$_POST['business']."', '".@$_POST['title']."', '".@$_POST['address']."', '".@$_POST['city']."', '".@$_POST['zip']."', '".@$_POST['phone']."', '".@$_POST['fax']."', '".@$_POST['mobile']."', '".@$_POST['category']."', '".@$_POST['comments']."', '".@$_POST['specialties']."', '".substr(strrchr($eg_uploadFile1, "/"), 1)."')", $eg_objConn1);
}


#8 Wintergreen

Wintergreen
  • Members
  • PipPipPip
  • Advanced Member
  • 107 posts

Posted 16 September 2006 - 09:00 PM

Look at the two main if statements you have, they're the same...
So if it goes into one, won't it also go into the other?  Why do you have an empty else statement sitting there?

Take a look at the first post I made in here.  The base is
if (any of the post variables are empty go here)
else (do what's in here)

#9 simcoweb

simcoweb
  • Members
  • PipPipPip
  • Advanced Member
  • 1,102 posts
  • LocationCA

Posted 16 September 2006 - 09:13 PM

Thanks, Wintergreen, for the further info. Actually I inserted your code but it produced parsing errors so i'm dealing with that.

To answer the other questions, the empty 'else' statement was just repositioning some stuff. The 2nd 'IF statment should disappear and all those items to parse should go in there. This is my assumption, obviously.

I placed your code at the beginning ahead of the current first IF statement. Since 'if' there's empty fields the validation shouldn't run anyway.

The real problem has been that even though the 'if' statements check for validation and empty fields, the form was still inserting the data into the mysql database. The page would display a validation error, for example, but it was still submitting the data. If i'm understanding your code it's basically going to stop the form from being submitted if a field is empty. But, let's say there's no empty fields but we still get a validation error. Is it going to stop the form from inserting the mysql query? That's really the root of all this.

Thanks again.

#10 Wintergreen

Wintergreen
  • Members
  • PipPipPip
  • Advanced Member
  • 107 posts

Posted 16 September 2006 - 09:26 PM

My code that I posted is an example from something I made, you would have to modify it to fit with your variable names etc.  I'm not quite sure how !empty($_POST) works, I haven't ever used it, but for that first IF statement, you're really trying to see if there IS anything empty, right?  Again I can't comment on using something like empty($_POST), but either way, you're trying to see if they're empty, not if they're full, so take the ! out of the first IF statement. 

As for your setup:
So the first big IF statement is just checking to see if the variables are empty or not.  If they are empty, it creates the error message.  If none of them are empty, you're wanting it to go into the second big IF, do a few more validation things and then if those turn out okay, insert to the DB.

So this would be the basic layout you'd want to use then:
if(any of the $_POST vars are empty) {
   check each one individually, if one is empty create the error message
   $header="form.php";  // or whatever page your original form is on
} else {  // So this else statement is only entered if all of the $_POST variables you checked above have something in them
   Here do your other validation statements for file size, etc.
   if(the validation turned out okay) {
      Insert info into the DB
      $header="success.php"; // Name of whatever page you want them to go to if everything is good
   } else {
      Something was wrong with the validation, so set any error message you want to display here
      $header="form.php";  // Again, take them back to the original page and display any problems
   }
}
header('location:$header');

So in the ELSE statement, there is another IF ELSE set.  It only enters here if the $_POST variables have datat in them.  Then it does the other validation you wanted.  If those turn out well, then it writes to the DB, if something is wrong, it enters the else loop.  Does this make more sense?

#11 simcoweb

simcoweb
  • Members
  • PipPipPip
  • Advanced Member
  • 1,102 posts
  • LocationCA

Posted 16 September 2006 - 09:50 PM

Just a quick note, I did modify your original code example to work with my form fields and also rearranged it a bit regarding the 'messages'.

Ok, your chronological order is correct. It should check IF there's a blank... then if there's not then it should check that the fields contain the proper characters (validation), if that checks out then run the query and complete the process. 

Now, it's actually doing the validation but as I mentioned it's submitting to the mysql even though there may be a validation error. The error is displayed and they are encouraged/told to correct the error and resubmit. Well, as it stands, if someone made a dozen errors then they will have submitted their data a dozen times. The 'empty($_POST) setup is really just a way to stop them from trying to submit the form with specific fields empty. It does not stop the form from running the query. That's the issue I really needs to resolve. The further validation and empty fields I can figure out. So, here's the lineup:

* person enters all fields but the passwords don't match - PRODUCES VALIDATION ERROR
* right there the form should STOP and not run the query
* person reenters the data correctly, validation is ok, and form checks for duplicate username
* IF the username already exists then it should STOP there and produce error 'username already exists. Please use another name'.
* person reenters the data with new username, validation is good to go, username has no dupes, and form data gets submitted.
* after submission they should be redirected to the 'login.php' page

I know that validation is different than an empty field so I need them both. If there's nothing to validate then it could slide through. So, i'll input that code and test it. The part that's missing is the code to STOP the data insertion.

Thanks again!

#12 simcoweb

simcoweb
  • Members
  • PipPipPip
  • Advanced Member
  • 1,102 posts
  • LocationCA

Posted 16 September 2006 - 10:05 PM

Just another quick note:

It didn't dawn on me until just now that the validation code already contains the if(empty) code as well:

// Validate users input
//if(!empty($_POST))
	// Check email is a valid email address
	if(isset($_POST['email'])) if(!ereg("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,}\\.[0-9]{1,}\\.[0-9]{1,}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,}|[0-9]{1,})(\\]?)$", $_POST['email'])) $eg_error['email'] = "You must enter a valid email address!";
	// Check password has a value
	if(empty($_POST['password'])) $eg_error['password'] = "You must enter a password!";
	// Check that confirmPass is the same as (comparison)
	if(isset($_POST['confirmPass'])) if($_POST['confirmPass'] != @$_POST['password']) $eg_error['confirmPass'] = "Your passwords do not match!";
	// Check that username is numbers and letters
	if(isset($_POST['username'])) if(ereg("[!\"£\$%\^&\*()\+=\{}[.].][.[.]#~';:@/\.,<>\?\\| ]", $_POST['username'])) $eg_error['username'] = "The user name contains some illegal charactures, only use alpha-numeric charactures.";
	// Check username has a value
	if(empty($_POST['username'])) $eg_error['username'] = "You must enter a user name!";
	// Check if any errors were returned and run relevant code
	if(empty($eg_error))
	{
	 
	}
	else
	{
	}
}

What's missing is the coding that is to run in the 'else' area with the key element being what happens when the validation doesn't jive. Again, the script is validating and producing the errors requiring them to re-enter but not stopping the form submission.

#13 Wintergreen

Wintergreen
  • Members
  • PipPipPip
  • Advanced Member
  • 107 posts

Posted 16 September 2006 - 10:07 PM

Post the input form you're using and I'll show you the first IF statement and what you'd do with it.  As for code to 'stop' it from entering into the DB, that's what the if else structure is for.  Anyway, post your form and I'll help you

#14 Wintergreen

Wintergreen
  • Members
  • PipPipPip
  • Advanced Member
  • 107 posts

Posted 16 September 2006 - 10:09 PM

The reason it's still entering into the DB is because you IF statements aren't done correctly yet

#15 simcoweb

simcoweb
  • Members
  • PipPipPip
  • Advanced Member
  • 1,102 posts
  • LocationCA

Posted 16 September 2006 - 10:17 PM

Exactly! That's the part of the code i'm looking for. As I mentioned, I have the validation and the 'if empty' parameters taken care of. What's missing is the STOP HERE AND DO NOT PROCESS part that's confusing me . Here's the form for your viewing pleasure:

<form id="Form1" style="WIDTH: 100%" name="Form1" method="post" enctype="multipart/form-data">
                                                                <table id="Table1" cellspacing="0" cols="2" cellpadding="0" width="400" align="center" border="0">
                                                                    <tbody>
                                                                        <tr>
                                                                            <td>
                                                                                <strong><font size="2">User Name:</font></strong></td>
                                                                            <td>
                                                                                <input id="username" maxlength="10" size="10" name="username" value="<?= @$_POST['username'] ?>"></td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td>
                                                                                <strong><font size="2">Password:</font></strong></td>
                                                                            <td>
                                                                                <input id="Password1" type="password" maxlength="10" size="12" name="password"></td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td>
                                                                                <strong><font size="2">Confirm Password:</font></strong></td>
                                                                            <td>
                                                                                <input id="Password2" type="password" maxlength="10" size="12" name="confirmPass"></td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td colspan="2">
                                                                                <hr>
                                                                            </td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td>
                                                                                <font size="2">First Name:</font></td>
                                                                            <td>
                                                                                <input id="firstname" maxlength="50" name="firstname" value="<?= @$_POST['firstname'] ?>"></td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td>
                                                                                <font size="2">Last Name:</font></td>
                                                                            <td>
                                                                                <input id="lastname" maxlength="50" name="lastname" value="<?= @$_POST['lastname'] ?>"></td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td>
                                                                                <font size="2">Email:</font></td>
                                                                            <td>
                                                                                <input id="email" maxlength="100" size="30" name="email" value="<?= @$_POST['email'] ?>"></td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td colspan="2">
                                                                                <hr>
                                                                            </td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td>
                                                                                <font size="2">Business Name:</font></td>
                                                                            <td>
                                                                                <input id="business" style="WIDTH: 211px; HEIGHT: 22px" size="28" name="business"></td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td>
                                                                                <font size="2">Title/Position:</font></td>
                                                                            <td>
                                                                                <input id="title" style="WIDTH: 211px; HEIGHT: 22px" size="28" name="title"></td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td>
                                                                                <font size="2">Address:</font></td>
                                                                            <td>
                                                                                <input id="address" style="WIDTH: 211px; HEIGHT: 22px" maxlength="20" size="24" name="address" value="<?= @$_POST['address'] ?>"></td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td valign="top">
                                                                                <font size="2">City:</font></td>
                                                                            <td>
                                                                                <input id="city" style="WIDTH: 115px; HEIGHT: 22px" size="15" name="city"></td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td>
                                                                                <font size="2">Zip&nbsp;Code:</font></td>
                                                                            <td>
                                                                                <input id="zipcode" maxlength="20" size="15" name="zip" value="<?= @$_POST['postCode'] ?>"></td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td colspan="2">
                                                                                <hr>
                                                                            </td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td>
                                                                                <font size="2">Phone:</font></td>
                                                                            <td>
                                                                                <input id="phone" maxlength="50" size="25" name="phone" value="<?= @$_POST['phone'] ?>"></td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td>
                                                                                <font size="2">Fax:</font></td>
                                                                            <td>
                                                                                <input id="fax" maxlength="50" size="25" name="fax" value="<?= @$_POST['fax'] ?>"></td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td>
                                                                                <font size="2">Mobile:</font></td>
                                                                            <td>
                                                                                <input id="mobile" maxlength="50" size="25" name="mobile" value="<?= @$_POST['mobile'] ?>"></td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td colspan="2">
                                                                                <hr>
                                                                            </td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td colspan="1">
                                                                                <font size="2">Category:</font></td>
                                                                            <td>
                                                                                <select id="DropDown1" style="WIDTH: 230px" name="category">
                                                                                    <option value="Marketing" selected="selected">Marketing
                                                                                    <option value="Professional Services">Professional Services
                                                                                    <option value="Health and Wellness">Health &amp; Wellness
                                                                                    <option value="Home Design and Improvements">Home Design &amp; Improvements
                                                                                </select></td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td valign="top">
                                                                                <font size="2">Details:</font></td>
                                                                            <td>
                                                                                <textarea id="TextArea2" name="comments" cols="30"><?= @$_POST['comments'] ?></textarea>
                                                                            </td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td valign="top">
                                                                                <font size="2">Specialties:</font></td>
                                                                            <td>
                                                                                <textarea id="TextArea2" name="specialties" cols="30"><?= @$_POST['specialties'] ?></textarea>
                                                                            </td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td colspan="1">
                                                                                <font size="2">Photo Upload:</font></td>
                                                                            <td>
                                                                                <input id="photo" type="file" name="photo"></td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td colspan="2">
                                                                                <hr>
                                                                                <font size="1">photo should be .jpg, .gif. or .png format under 100k (bytes)</font> 
                                                                                <br>
                                                                            </td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td>
                                                                            </td>
                                                                            <td align="right">
                                                                                <input id="Submit1" type="submit" value="Register"></td>
                                                                        </tr>
                                                                    </tbody>
                                                                </table>
                                                            </form>


#16 Wintergreen

Wintergreen
  • Members
  • PipPipPip
  • Advanced Member
  • 107 posts

Posted 17 September 2006 - 12:12 AM

What I'm saying is, you don't ever have to explicitly say 'don't insert into the DB'.  It happens automatically with the IF ELSE statements.  You just have to learn to set them up correctly

if( (empty($_POST['username']) || (empty($_POST['password']) || (empty($_POST['confirmPass']) || ($_POST['password'] != $_POST['confirmPass']) || (empty($_POST['firstname']) || (empty($_POST['lastname']) || (empty($_POST['email']) || (empty($_POST['business']) || (empty($_POST['title']) || (empty($_POST['address']) || (empty($_POST['city']) || (empty($_POST['zip']) || (empty($_POST['phone']) || (empty($_POST['fax']) || (empty($_POST['mobile']) || (empty($_POST['comments']) || (empty($_POST['specialties']) || (empty($_POST['photo']) ) {
Here's where you check the values and create your messages, like 'you must have a username', 'your passwords don't match'.
So as an example,

   if (empty($_POST['username']) {
      $eg_error['username'] = "You need a username.";
   if ($_POST['password'] != $_POST['confirmPass']) {
      $eg_error['confirmPass'] = "Your passwords do not match.";
   }
}

Now, in this format, ALL fields are required to have data or the form will not go into the else loop that does your second round of checks.  See how this works?  If you want to make some of the fields optional, then take their respective check out of that if statement. 

#17 simcoweb

simcoweb
  • Members
  • PipPipPip
  • Advanced Member
  • 1,102 posts
  • LocationCA

Posted 17 September 2006 - 12:58 AM

Ok, I understand that part. I have that code already as shown below:

if(!empty($_POST))
	// Check email is a valid email address
	if(isset($_POST['email'])) if(!ereg("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,}\\.[0-9]{1,}\\.[0-9]{1,}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,}|[0-9]{1,})(\\]?)$", $_POST['email'])) $eg_error['email'] = "You must enter a valid email address!";
	// Check password has a value
	if(empty($_POST['password'])) $eg_error['password'] = "You must enter a password!";
	// Check that confirmPass is the same as (comparison)
	if(isset($_POST['confirmPass'])) if($_POST['confirmPass'] != @$_POST['password']) $eg_error['confirmPass'] = "Your passwords do not match!";
	// Check that username is numbers and letters
	if(isset($_POST['username'])) if(ereg("[!\"£\$%\^&\*()\+=\{}[.].][.[.]#~';:@/\.,<>\?\\| ]", $_POST['username'])) $eg_error['username'] = "The user name contains some illegal charactures, only use alpha-numeric charactures.";
	// Check username has a value
	if(empty($_POST['username'])) $eg_error['username'] = "You must enter a user name!";
	// Check if any errors were returned and run relevant code
	if(empty($eg_error))
	{
	echo "You must complete all the form fields before submitting." ;
	}
	else
	{
	  //check if username already exists
	  $sql_user_check = "SELECT * FROM plateau_pros WHERE username='$username'";
      $result_name_check = mysql_query($sql_user_check);
      $usersfound = mysql_num_rows($result_name_check);
    }
// if user  found, note that and end
if ($usersfound > 0) {
    $error = "Username $user is already in use. Please choose another username.";
	} else
	{

The validation and empty field check is doing fine. But it's not stopping the form from submitting the data. I don't know if I can make it any clearer but ... the validation errors appear to the user but it's not stopping the query entering the info into the database. I'm looking specifically for the code snippet that prevents that. In a plain logical way it would work like this:

if(check for empties..if empty ..halt... show error messages for fields not completed properly....user inputs new data..hits submit... it validates again...if ok then goes to 'else')
else(if no errors as above...upload photo...run query...redirect to 'login.php')

Right now what's happening is:

if(check for empties... finds fields that violate validation rules... runs the mysql query..uploads the file...then returns to the form to display the error messages which makes it look to the user like nothing happened..user re-inputs the data and uploads again duplicating the records)


In my limited knowledge I look at the code i'm using and see this:

if(check user input to make sure username/password/confirmpass have entries... check same fields for type of input...if errors display error messages..if no errors proceed to next step which is username check... run username check if no errors..if no username match found then proceed to next step which is file upload, query, etc.)

What i'm in need of is the correct code to stop this duplication of the same username and prevent the query from happening until there's no errors in the input.

I'm reading you loud and clear on the part you've posted but that's just one part of the equation. Make sense?

I do appreciate your posts. Just not sure if we're looking at the same part of the problem :)




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users