Jump to content

pre-populating field with data that the user just entered. (registration form)


phpchick
 Share

Recommended Posts

I just tested the code, commenting out db connections and it is repopulating the fields and the error checks are displaying 1 by 1, I have modified it a little bit copy it in full and just edit your db fields back to the correct values, it does work.

 

I have also attached the code so you can just get the complete script

 

<?php
define('DB_NAME', 'dbname');
define('DB_USER', 'username');
define('DB_PASS', 'pass');
define('DB_HOST', 'server.sql.com');

// contact to database
$connect = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die('Error , check your server connection.');
mysql_select_db(DB_NAME);
  
if ($_SERVER['REQUEST_METHOD']=='POST') {

// get variables
$name=$_POST['name'];
$email=$_POST['email'];
$msg=$_POST['msg'];

// check valid email
function check_email_address($email) {
    // First, we check that there's one @ symbol, and that the lengths are right
    if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
        // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
        return false;
    }
    // Split it into sections to make life easier
    $email_array = explode("@", $email);
    $local_array = explode(".", $email_array[0]);
    for ($i = 0; $i < sizeof($local_array); $i++) {
         if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
            return false;
        }
    }    
    if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
        $domain_array = explode(".", $email_array[1]);
        if (sizeof($domain_array) < 2) {
                return false; // Not enough parts to domain
        }
        for ($i = 0; $i < sizeof($domain_array); $i++) {
            if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
                return false;
            }
        }
    }
    return true;
}

// check for errors here
if (strlen($msg) <  $aError[] = 'Password must be at least 8 characters.';
if ($msg == strtolower($msg))	$aError[] = 'Password must have at least 1 uppercase.';
if (preg_replace("/[^a-zA-Z0-9\s]/", "", $msg) == $msg) $aError[] = 'Password must have a least one special character.';
if (strcspn($msg, '0123456789') == strlen($msg)) $aError[] = 'Password must one at least one number.';
if ($name == "" || $msg == "" ) $aError[] = 'Please enter a password.';
if (check_email_address($name)  == false) $aError[] = 'Please enter a valid email.';   

// NO ERRERS  process form
if (count($aError) == 0) {
// --process form here--
echo 'SQL SERVER MESSUP YOU BLEW UP MESSAGE';
$query = "INSERT INTO contact(name,email,msg) VALUES ('$name','$email','$msg')";

	if (!$result) { die( mysql_error()); }
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>SiteIS</title>
<link rel="stylesheet" type="text/css" href="http://site.com/signup.css">
</head>
<body>
<div class="main">

<!--  BEGIN LEFT -->
<div class="left">
<h1>Why join?</h1>
<div class="body">siteis the web's most robust research company with a universe of over 100 .</div><br>
<img src="http://site.com/joined.png" alt="Over 000 have already joined."  width="170" height="70"/>
</div>

<!--  BEGIN CENTER -->
<div class="center">
<h1>Join free:</h1>
<form action="" method="POST" id="insert">                        
	<div class="labels">Name:</div>
    	<input type="text" size=28 name="name" <?php if (isset($name) && $name!="") { echo "value='$name'"; } ?>>
	<div class="labels">Email Address</div>
    	<input type="text" size=28 name="email" <?php if (isset($email) && $email!="") { echo "value='$email'"; } ?>>
    	<div class="labels">Choose Password</div>
	<input type="password" size=28  name="msg" <?php if (isset($msg) && $msg!="") { echo "value='$msg'"; } ?>>
	<?php if (isset($aError) && $aError!="") { echo "<div class='error'>".$aError[0]."</div>"; } ?>
	<div class="agreeterms"><Input type='checkbox' Name='gender' checked="checked">I agree to terms and privacy policy</div>
	<div class="joinbutton"><input type="submit" name="submit" value="Join"></div>
	<div class="agreeterms"><a href="">Click here to log in</a></div><br><br><br>
</form>
</div>
<!--  BEGIN RIGHT -->
</body>
</html>

 

I have not checked or done any editing of your error checking rules but it does go through them.

 

[attachment deleted by admin]

Link to comment
Share on other sites

Whoa! Glancing at your code tells me that there are some bad tendencies that you have when writing code. Try this:

 

<?php

define('DB_NAME', 'dbname');
define('DB_USER', 'username');
define('DB_PASS', 'pass');
define('DB_HOST', 'server.sql.com');

// contact to database
$connect = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die('Error , check your server connection.');
mysql_select_db(DB_NAME);

// get & set variables
if ($_SERVER['REQUEST_METHOD']=='POST') {
	$name = $_POST['name'];
	$email = $_POST['email'];
	$msg = $_POST['msg'];
} else {
	$name = '';
	$email = '';
	$msg = '';
}

if ($_SERVER['REQUEST_METHOD']=='POST') {
	// check for errors here
	if (strlen($msg) <  $aError[] = 'Password must be at least 8 characters.';
	if ($msg == strtolower($msg))	$aError[] = 'Password must have at least 1 uppercase.';
	if (preg_replace("/[^a-zA-Z0-9\s]/", "", $msg) == $msg) $aError[] = 'Password must have a least one special character.';
	if (strcspn($msg, '0123456789') == strlen($msg)) $aError[] = 'Password must one at least one number.';
	if ($name == "" || $msg == "" ) $aError[] = 'Please enter a password.';
	if (check_email_address($name)  == false) $aError[] = 'Please enter a valid email.';   

	// NO ERRERS  process form
	if (count($aError) == 0) {
		// --process form here--
		echo 'SQL SERVER MESSUP YOU BLEW UP MESSAGE';
		$query = "INSERT INTO contact(name,email,msg) VALUES ('$name','$email','$msg')";
		$result = mysql_query( $query );
		if (!$result) { die( mysql_error()); }
	}
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Siteis</title>
<link rel="stylesheet" type="text/css" href="http://site.com/signup.css">
</head>
<body>

<div class="main">
<!--  BEGIN LEFT -->
<div class="left">
	<h1>Why join?</h1>
	<div class="body">siteis the web's most robust research company with a universe of over 100 .</div><br>
	<img src="http://site.com/joined.png" alt="Over 000 have already joined."  width="170" height="70"/>
</div>

<!--  BEGIN CENTER -->
<div class="center">
	<h1>Join free:</h1>

	<form action="" method="POST" id="insert">
		<div class="labels">Name:</div><input type="text" size="28" name="name" value="<?php echo $name; ?>" />
		<div class="labels">Email Address</div><input type="text" size="28" name="email" value="<?php echo $email; ?>" />
		<div class="labels">Choose Password</div><input type="password" size="28" name="msg">

		<?php if (isset($aError[0]) && $aError[0]!="") { ?>
			<div class="error"><?php echo $aError[0]; ?></div>
		<?php } ?>
		<div class="agreeterms"><input type="checkbox" name="gender" checked="checked">I agree to terms and privacy policy</div>
		<div class="joinbutton"><input type="submit" name="submit" value="Join"></div>
		<div class="agreeterms"><a href="">Click here to log in</a></div>

		<br /><br /><br />
	</form>
</div>
<!--  BEGIN RIGHT -->
</div>

</body>
</html>

<?php

// check valid email
function check_email_address($email) {
	// First, we check that there's one @ symbol, and that the lengths are right
	if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
		// Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
		return false;
	}

	// Split it into sections to make life easier
	$email_array = explode("@", $email);
	$local_array = explode(".", $email_array[0]);

	for ($i = 0; $i < sizeof($local_array); $i++) {
		if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
			return false;
		}
	}

	if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
		$domain_array = explode(".", $email_array[1]);

		if (sizeof($domain_array) < 2) {
			return false; // Not enough parts to domain
		}

		for ($i = 0; $i < sizeof($domain_array); $i++) {
			if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
				return false;
			}
		}
	}

	return true;
}

?>

 

First, your code was outside of your beginning body tag. Second, you had no ending div tag. Third, try to keep your functions outside of your logic, like at the bottom of the script.

 

I do want to warn you. I test the code above (commenting out the SQL stuff) and when I entered information correct, the fields pre-populated as you want however, it says my email address was bad. I highly suggest you check the regular expressions that you are using. There is no need to use more than one regular expression when checking the validation of an email address. Here is the one that I use and how I use it:

 

/^[A-Z0-9._%\-+]+@[A-Z0-9][A-Z0-9.-]{0,61}[A-Z0-9]\.[A-Z]{2,6}$/i

if (!preg_match($emailPattern, $_POST['email'])) {
$error['email'] = '<strong>Error:</strong> Email address is not valid!';
}

Link to comment
Share on other sites

actually the body and missing div tag was my fault going to quick trying to patch up the chaos when adding the doctype and html formatting that wasnt there before. I didnt notice that I had done that at the time. :)

Link to comment
Share on other sites

I want to log into the DB everything the user enters, including when it does not satisfy the requirements, so I modified your code dragon to this.

 

it does the trick, but it logs every condition that is satisfied, so there are multiple entries for each 1 entry. Is there a quick way to fix this?

 

If not I will just leave it as I just want to get it up and running at this point. 

 

and then do a select * from table group by in the db to parse out the duplicates

 


if (check_email_address($name)  == false) $aError[] = 'Please enter a valid email.';  

$query = "INSERT INTO contact(name,email,msg) VALUES ('$name','$email','$msg')";
	$result = mysql_query( $query );

	if( !$result ) {
		die( mysql_error() );
	}

if (strlen($msg) <  $aError[] = 'Password must be at least 8 characters.';

$query = "INSERT INTO contact(name,email,msg) VALUES ('$name','$email','$msg')";
	$result = mysql_query( $query );

	if( !$result ) {
		die( mysql_error() );
	}

if ($msg == strtolower($msg))	$aError[] = 'Password must have at least 1 uppercase.';

$query = "INSERT INTO contact(name,email,msg) VALUES ('$name','$email','$msg')";
	$result = mysql_query( $query );

	if( !$result ) {
		die( mysql_error() );
	}

if (preg_replace("/[^a-zA-Z0-9\s]/", "", $msg) == $msg) $aError[] = 'Password must have a least one special character.';

$query = "INSERT INTO contact(name,email,msg) VALUES ('$name','$email','$msg')";
	$result = mysql_query( $query );

	if( !$result ) {
		die( mysql_error() );
	}

if (strcspn($msg, '0123456789') == strlen($msg)) $aError[] = 'Password must one at least one number.';

$query = "INSERT INTO contact(name,email,msg) VALUES ('$name','$email','$msg')";
	$result = mysql_query( $query );

	if( !$result ) {
		die( mysql_error() );
	}

if ($name == "" || $msg == "" ) $aError[] = 'Please enter a password.';

$query = "INSERT INTO contact(name,email,msg) VALUES ('$name','$email','$msg')";
	$result = mysql_query( $query );

	if( !$result ) {
		die( mysql_error() );
	}

Link to comment
Share on other sites

You want to have multiple sign up entries even when some of the data is incorrect?

 

if that is the case dont have the insert query twice, just leave the code as it is and remove the following line

 

if (count($aError) == 0) {

 

and also the } on line 62

 

I dont really think this is wise though.

 

also you should change line 14 to

 

$name=mysql_real_escape_string($_POST['name']);

 

as a means to avoid sql injections, also I would use password encryption techniques such as md5 plus salt.

I havent gone into a lot of detail with that but they are not hard to implement.

Link to comment
Share on other sites

You sure do like to repeat code.

 

At the point where you have finished validating all the data, you would either insert the successful data (what your code is doing now before your latest post above) or you would log the reason(s) for the unsuccessful attempt -

 

if (count($aError) == 0) {
// --process form here--
......
} else {
    // log the reason(s) for the unsuccessful attempt here...

}

 

Since this is a registration form/scirpt, you wouldn't log the unsuccessful information into the same table (which is what the query you just posted above is doing) where you are inserting your successful form submissions.

Link to comment
Share on other sites

When you say "leave the code as it is" do you mean after I made the revisions (in reply #30) or do you mean in your original test3.php ?

 

 

You want to have multiple sign up entries even when some of the data is incorrect?

 

if that is the case dont have the insert query twice, just leave the code as it is and remove the following line

 

if (count($aError) == 0) {

 

and also the } on line 62

 

I dont really think this is wise though.

 

also you should change line 14 to

 

$name=mysql_real_escape_string($_POST['name']);

 

as a means to avoid sql injections, also I would use password encryption techniques such as md5 plus salt.

I havent gone into a lot of detail with that but they are not hard to implement.

Link to comment
Share on other sites

 

 

also you should change line 14 to

 

$name=mysql_real_escape_string($_POST['name']);

 

as a means to avoid sql injections, also I would use password encryption techniques such as md5 plus salt.

I havent gone into a lot of detail with that but they are not hard to implement.

 

should I change the others with the same syntax also?

 

$name=mysql_real_escape_string($_POST['name']);
$email=$_POST['email'];
$msg=$_POST['msg'];

 

 

Link to comment
Share on other sites

The original code and yes use mysql_escape_string on all data inputted from users that will go into a database.

 

I removed

 

if (count($aError) == 0) { 

 

and the } from line 62 as you suggested but now there is a different behaviour.

 

No matter what happens, it will execute the script as if there are no errors, even if there are. Does that make sense?

 

Everything is directed to the no errors processing form now.

 

Link to comment
Share on other sites

I got it!!!!

 

 

this is what I eventually did

 

 

// --process form here--
if (count($aError) == 0) {
$query = "INSERT INTO contactv3(name,email,msg) VALUES ('$name','$email','$msg')";
$result = mysql_query( $query );
	if (!$result) { die( mysql_error()); }

	if(!isset($_SESSION['SESS_USERID'])||(trim($_SESSION['SESS_USERID']=='admin'))) 
    { 
        echo '<script language="javascript">'; 
        echo 'top.location.href = "http://www.ceofinity.com/404.html";'; 
        echo '</script>'; 
        exit(); 
    } 
}
else		

$query = "INSERT INTO contactv3(name,email,msg) VALUES ('$name','$email','$msg')";
	$result = mysql_query( $query );

	if( !$result ) {
		die( mysql_error() );
	}

}

 

Thank you SO MUCH dragon_sa, you have no idea how much you've helped me learn with this exercise.

Link to comment
Share on other sites

No problem, happy to help, on your else statement where you insert

 

else		

$query = "INSERT INTO contactv3(name,email,msg) VALUES ('$name','$email','$msg')";
	$result = mysql_query( $query );

	if( !$result ) {
		die( mysql_error() );
	}

}

 

I would log those in a different table like contactErrorv3 for example, so your successful and unsuccessful inputs are separated. The table can be identical to the contactv3 table, this way you wont get a bloated table of successful contacts mixed with unsuccessful attempts.

Link to comment
Share on other sites

This thread is more than a year old.

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.

 Share

×
×
  • 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.