Jump to content

Recommended Posts

I'm making a page that asks you to put in your first name, last name, and email address. I want php to check every field against preg, and if everyone passes, then allow it to insert it into the database. Othrwise, I want it to print the error message.

 

I think I'm really overthinking this one. I can't get it right. It worked once, a different way but the error messages came up once the page loaded. I probably don't even need the counter, but I was desperate!

 

Please help?

 

<?php$
firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$emailaddy = $_POST['email'];
$doubleaddycheck = "SELECT * FROM emaillist WHERE email = $emailaddy";
$doubleaddycheck = mysql_query($doubleaddycheck);
$insertcontactdata = "INSERT INTO emaillist (email, firstname, lastname) VALUES ('$emailaddy2', '$firstname2', '$lastname2')";

$counter = 1;


if ($_POST['email']) {

if (!preg_match('/^[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+(?:\.[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+)*\@[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+(?:\.[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+)+$/i', $emailaddy)) {print "Please enter a valid e-mail address.<br />";} 

elseif (mysql_num_rows($doubleaddycheck) > 0) {print "That e-mail address has already been added!";} 

else {

$emailaddy2 = $_POST['email'];

$counter = $counter++;}

}

if ($_POST['firstname']) {

if (!preg_match("/^[a-z\\\'\-\s]+$/i", $firstname)) {print "Please enter a valid first name.<br />";} 

  	elseif (strlen($firstname) < 1) {print "Please enter a valid first name.";}

  	else {

  	$firstname2 = $_POST['firstname'];

  	$counter = $counter++;}

}

if ($_POST['lastname']){

  	if (!preg_match("/^[a-z\\\'\-\s]+$/i", $lastname)) {print "Please enter a valid last name.<br />";}

  	elseif (strlen($lastname)< 1) {print "Please enter a valid last name.";} 

  	else {

  	$lastname2 = $_POST['lastname'];

$counter = $counter++;}

}

if ($counter == 4) {

mysql_query($insertcontactdata);

print "Welcome to the list<b> $firstname! </b><br />\n";

print "Your e-mail address: <b> $emailaddy </b>will be included in future e-mails.";

}

?>

Link to comment
https://forums.phpfreaks.com/topic/105347-solved-form-validation-o-multiple-forms/
Share on other sites

<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$emailaddy = $_POST['email'];
$doubleaddycheck = "SELECT * FROM emaillist WHERE email = $emailaddy";
$doubleaddycheck = mysql_query($doubleaddycheck);
$insertcontactdata = "INSERT INTO emaillist (email, firstname, lastname) VALUES ('$emailaddy2', '$firstname2', '$lastname2')";

$errors = array();


if ($_POST['email']) {

if (!preg_match('/^[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+(?:\.[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+)*\@[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+(?:\.[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+)+$/i', $emailaddy)) {
	$errors[] = "Please enter a valid e-mail address.";
} elseif (mysql_num_rows($doubleaddycheck) > 0) {
	$errors[] = "That e-mail address has already been added!";
} else {
	$emailaddy2 = $_POST['email'];
}

}

if ($_POST['firstname']) {

if (!preg_match("/^[a-z\\\'\-\s]+$/i", $firstname)) {
	$errors[] = "Please enter a valid first name.";
} elseif (strlen($firstname) < 1) {
	$errors[] = "Please enter a valid first name.";
} else {
  		$firstname2 = $_POST['firstname'];
}

}

if ($_POST['lastname']){

  	if (!preg_match("/^[a-z\\\'\-\s]+$/i", $lastname)) {
	$errors[] = "Please enter a valid last name.";
} elseif (strlen($lastname)< 1) {
	$errors[] = "Please enter a valid last name.";
} else {
  		$lastname2 = $_POST['lastname'];
}
}

if (empty($errors) { //if the array $errors is empty(everything passed) continue with the script and add the person.

mysql_query($insertcontactdata);

print "Welcome to the list<b> $firstname! </b><br />\n";

print "Your e-mail address: <b> $emailaddy </b>will be included in future e-mails.";

} else { //the array has an error in it, print the error.
echo 'Error <p>The following errors occured:<br />';
foreach ($errors as $msg) {
	echo " - $msg\n";
}
echo '</p><p>Plese try again.</p>';
}

?>

 

Try that, i had to realign the code alot 0.o i didn't know if it was so far off becuase of this [ code ]... w/e.

 

I use an error array and then check to make sure the array is empty. If not then print the error messages.

 

Try that, i had to realign the code alot 0.o i didn't know if it was so far off becuase of this [ code ]... w/e.

 

I use an error array and then check to make sure the array is empty. If not then print the error messages.

 

Thanks! I actually am getting the dreaded white screen from that, so there must be an error somewhere. I'm looking now...

 

My code was poorly aligned, but not as bad as it looked in here. For some reason when I pasted it in here it did weird things..

Thanks, that was the error. However this code isn't working for me at all. Once you navigate to the page it inserts all the blank fields into the database and prints the "Thanks, your email will be included". Then if you try and insert real data in all 3 fields, it will not insert them into the datasbase.

On your IF statements change ad !empty... for example if (!empty($_POST['firstname'])) { ... etc

 

Then add:

 

else {

  $errors[] = "Error message here";

}

 

to the end of the if's

 

One example:

if (!empty($_POST['firstname'])) {

if (!preg_match("/^[a-z\\\'\-\s]+$/i", $firstname)) {
	$errors[] = "Please enter a valid first name.";
} elseif (strlen($firstname) < 1) {
	$errors[] = "Please enter a valid first name.";
} else {
  		$firstname2 = $_POST['firstname'];
}

} else {
  $errors[] = "No name?";
}

 

P.S. The [ b ] was me trying to bold the text i added, but it failed.

On your IF statements change ad !empty... for example if (!empty($_POST['firstname'])) { ... etc

 

Then add:

 

else {

   $errors[] = "Error message here";

}

 

to the end of the if's

 

One example:

 

Thanks, this helped, however the new error messages now show up immediately when I navigate to the page.

Here's my current code. It's doing like I said in my previous post. Showing error messages immediately and not inserting any data into db even when the forms are filled correctly. I really appreciate any help!

 

<?php

$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$emailaddy = $_POST['email'];
$doubleaddycheck = "SELECT * FROM emaillist WHERE email = $emailaddy";
$doubleaddycheck = mysql_query($doubleaddycheck);
$insertcontactdata = "INSERT INTO emaillist (email, firstname, lastname) VALUES ('$emailaddy2', '$firstname2', '$lastname2')";

$errors = array();

if (!empty($_POST['email'])) {
if (!preg_match('/^[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+(?:\.[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+)*\@[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+(?:\.[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+)+$/i', $emailaddy)) {
	$errors[] = "Please enter a valid e-mail address.";
} elseif (mysql_num_rows($doubleaddycheck) > 0) {
	$errors[] = "That e-mail address has already been added!";
} else {
	$emailaddy2 = $_POST['email'];
}
} else {
  $errors[] = "Please enter an e-mail address";
}

if (!empty($_POST['firstname'])) {
if (!preg_match("/^[a-z\\\'\-\s]+$/i", $firstname)) {
	$errors[] = "Please enter a valid first name.";
} elseif (strlen($firstname) < 1) {
	$errors[] = "Please enter a valid first name.";
} else {
  		$firstname2 = $_POST['firstname'];
}
} else {
  $errors[] = "Please enter a first name.";
}

if (!empty($_POST['lastname'])){
  	if (!preg_match("/^[a-z\\\'\-\s]+$/i", $lastname)) {
	$errors[] = "Please enter a valid last name.";
} elseif (strlen($lastname)< 1) {
	$errors[] = "Please enter a valid last name.";
} else {
  		$lastname2 = $_POST['lastname'];
}
} else {
  $errors[] = "Please Enter a last name.";
}


if (empty($errors)) { //if the array $errors is empty(everything passed) continue with the script and add the person.
mysql_query($insertcontactdata);
print "Welcome to the list<b> $firstname! </b><br />\n";
print "Your e-mail address: <b> $emailaddy </b>will be included in future e-mails.";

} else { //the array has an error in it, print the error.
foreach ($errors as $msg) {
	echo " - $msg\n";
}
}

<?

This is completely re-written. You need to change 1 thing, on the form that submits to this page, you need to add:

<input type="hidden" name="submitted" value="TRUE" />

 

Anywhere in between the <form> and </form> i usually put mine just before </form>

 

Final code:

<?php
function escape_data($data) {
if (ini_get('magic_quotes_gpc')){
	$data = stripslashes($data);
}
if(function_exists('mysql_real_escape_string')) {
	global $dbc;
	$data = mysql_real_escape_string(trim($data), $dbc);
}
return $data;
}

if (isset($_POST['submitted'])) { // Handle the form.

require_once ('./includes/mysql_connect.php'); // Connect to the database.

//check for email address
if (strlen($_POST['email']) <= 40) {
	if (eregi ('^[[:alnum:]][a-z0-9_\.\-]*@[a-z0-9\.\-]+\.[a-z]{2,4}$', stripslashes(trim($_POST['email'])))) {
		$e = escape_data($_POST['email']);
	} else {
		$e = FALSE;
		echo '<p><font color="red" size="+1">Please enter a valid email address!</font></p>';
	}
} else {
	$e = FALSE;
	echo '<p>The email address you provided exceeds maximum length of 40 letters</p>';
}

// Check for a first name.
if (strlen($_POST['firstname']) <= 20) {
	if (eregi ('^[[:alpha:]\.\' \-]{2,15}$', stripslashes(trim($_POST['firstname'])))) {
		$fn = escape_data($_POST['firstname']);
		$fn = ucwords($fn);
	} else {
		$fn = FALSE;
		echo '<p><font color="red" size="+1">Please enter your first name!</font></p>';
	}
} else {
	$fn = FALSE;
	echo '<p>First Name exceeds maximum length of 20 letters</p>';
}

// Check for a last name.
if (strlen($_POST['lastname']) <= 40) {
	if (eregi ('^[[:alpha:]\.\' \-]{2,30}$', stripslashes(trim($_POST['lastname'])))) {
		$ln = escape_data($_POST['lastname']);
		$ln = ucwords($ln);
	} else {
		$ln = FALSE;
		echo '<p><font color="red" size="+1">Please enter your last name!</font></p>';
	}
} else {
	$ln = FALSE;
	echo '<p>Last Name exceeds maximum length of 40 letters</p>';
}

if ($fn && $ln && $e) { // If everything's OK.

	// Make sure the email address is available.
	$query = "SELECT * FROM emaillist WHERE email='$e'";		
	$result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());

	if (mysql_num_rows($result) == 0) { // Available.

		// Add the user.
		$query = "INSERT INTO emaillist (email, firstname, lastname) VALUES ('$e', '$fn', '$ln')";		
		$result = mysql_querry ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());

		if (mysql_affected_rows() == 1) { // If it ran OK.
			// Finish the page.
			echo 'Welcome to the list, <b>$fn!</b><br />\nYour e-mail address: <b>$e</b> will be included in future e-mails.';
			exit(); // exit the rest of the script.
		} else { // If it did not run OK.
			echo '<p><font color="red" size="+1">You could not be registered due to a system error. We apologize for any inconvenience.</font></p>'; 
		}		
	} else { // The email address is not available.
		echo '<p><font color="red" size="+1">That email address has already been registered.</font></p>'; 
	}

} else { // If one of the data tests failed.
	echo '<p><font color="red" size="+1">Please try again.</font></p>';		
}

mysql_close(); // Close the database connection.

} else {
        echo "You have accessed this page in error!";
} // End of the main Submit conditional.

?>

 

If your coding on your original page is correct, like the mysql querys and everything, i'm pretty sure this should work right off the bat.

This is completely re-written. You need to change 1 thing, on the form that submits to this page, you need to add:

<input type="hidden" name="submitted" value="TRUE" />

 

Anywhere in between the <form> and </form> i usually put mine just before </form>

 

Whoa, that's a lot of stuff I haven;t seen before haha, but yes, it works! Great! Thanks so much for all your help!

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.