Jump to content

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


phpchick

Recommended Posts

I'm building a php program that registers users onto a website. With the help of people from this thread http://www.phpfreaks.com/forums/index.php?topic=332260.15

I was able to accomplish the goal and now the signup works with conditions that check for a valid email, and if the password is strong enough.

 

T he program correctly displays the the problem when a user does NOT enter a valid email, or a strong enough password, but the user has to re-enter the email and password everytime.

 

I want to make it so that the fields remained populated with what the user entered previously, so he or she does not have to re-enter his or her email/password.

 

Here is the code (its really ghetto)

 

<?php

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;
}

define('DB_NAME', 'catch');
define('DB_USER', 'username');
define('DB_PASS', 'password');
define('DB_HOST', 'page.sqlserver.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 data in local variable
$v_name=$_POST['name'];
$v_email=$_POST['email'];
$v_msg=$_POST['msg'];


if ( check_email_address($_POST['name'])  == false) 


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

	if( !$result ) {
		die( mysql_error() );
	}
	echo <<<EOD
		<head>      
			<link rel="stylesheet" type="text/css" href="http://hedgezoo.com/signup.css">
		</head>
		<h2>Free Registration</h2>
		<form action="contact_insert2.php" method="POST" id="insert">
			<table>
				<tr>
					<td>Email</td>
					<td ><input type="text" size="40" name="name"></td>
				</tr>
			    <tr>
					<td>Password</td>
					<td><input type="password" size="40"  name="msg" ></td>
				</tr>
				<tr>
					<td colspan=2 id="sub">
						You must enter a valid email. <br />
						<input type="submit" name="submit" value="submit">
					</td>
				</tr>
			</Table>
		</form>
EOD;
}

if( $v_name == "" || $v_msg == "" )
// if name is empty or if pass is empty
{
	$query = "INSERT INTO contact(name,email,msg) VALUES ('$v_name','$v_email','$v_msg')";
	$result = mysql_query( $query );

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

	echo <<<EOD
		<head>      
			<link rel="stylesheet" type="text/css" href="http://hedgezoo.com/signup.css">
		</head>
		<h2>Free Registration</h2>
		<form action="contact_insert2.php" method="POST" id="insert">
			<table>
				<tr>
					<td>Email</td>
					<td ><input type="text" size="40" name="name"></td>
				</tr>
			    <tr>
					<td>Password</td>
					<td><input type="password" size="40"  name="msg" ></td>
				</tr>
				<tr>
					<td colspan=2 id="sub">
						You must enter an email and password. <br />
						<input type="submit" name="submit" value="submit">
					</td>
				</tr>
			</Table>
		</form>
EOD;
}

if( strcspn( $_REQUEST['msg'], '0123456789' ) == strlen( $_REQUEST['msg'] ) )
// the above statement says if pass does not contain a number
{
	$query = "INSERT INTO contact(name,email,msg) VALUES ('$v_name','$v_email','$v_msg')";
	$result = mysql_query( $query );

	if( !$result ) {
		die( mysql_error() );
	}
	echo <<<EOD
		<head>      
			<link rel="stylesheet" type="text/css" href="http://hedgezoo.com/signup.css">
		</head>
		<h2>Free Registration</h2>
		<form action="contact_insert2.php" method="POST" id="insert">
			<table>
				<tr>
					<td>Email</td>
					<td ><input type="text" size="40" name="name"></td>
				</tr>
			    <tr>
					<td>Password</td>
					<td><input type="password" size="40"  name="msg" ></td>
				</tr>
				<tr>
					<td colspan=2 id="sub">
						<div style="color:red;">Your password must contain a number.</div> <br />
						<input type="submit" name="submit" value="submit">
					</td>
				</tr>
			</Table>
		</form>
EOD;
}


if( strlen($_POST['msg']) < 8 )
// the above statement says if pass is not 8 characters long
{
	$query = "INSERT INTO contact(name,email,msg) VALUES ('$v_name','$v_email','$v_msg')";
	$result = mysql_query( $query );

	if( !$result ) {
		die( mysql_error() );
	}
	echo <<<EOD
		<head>      
			<link rel="stylesheet" type="text/css" href="http://hedgezoo.com/signup.css">
		</head>
		<h2>Free Registration</h2>
		<form action="contact_insert2.php" method="POST" id="insert">
			<table>
				<tr>
					<td>Email</td>
					<td ><input type="text" size="40" name="name"></td>
				</tr>
			    <tr>
					<td>Password</td>
					<td><input type="password" size="40"  name="msg" ></td>
				</tr>
				<tr>
					<td colspan=2 id="sub">
						<div style="color:red;">Your password must be at least 8 characters long.</div> <br />
						<input type="submit" name="submit" value="submit">
					</td>
				</tr>
			</Table>
		</form>
EOD;
}


	if ( $_POST['msg'] == strtolower($_POST['msg']) )
// the above statement says if pass is all lowercase
{
	$query = "INSERT INTO contact(name,email,msg) VALUES ('$v_name','$v_email','$v_msg')";
	$result = mysql_query( $query );

	if( !$result ) {
		die( mysql_error() );
	}
	echo <<<EOD
		<head>      
			<link rel="stylesheet" type="text/css" href="http://hedgezoo.com/signup.css">
		</head>
		<h2>Free Registration</h2>
		<form action="contact_insert2.php" method="POST" id="insert">
			<table>
				<tr>
					<td>Email</td>
					<td ><input type="text" size="40" name="name"></td>
				</tr>
			    <tr>
					<td>Password</td>
					<td><input type="password" size="40"  name="msg" ></td>
				</tr>
				<tr>
					<td colspan=2 id="sub">
						<div style="color:red;">Your password must have at least one capital letter.</div> <br />
						<input type="submit" name="submit" value="submit">
					</td>
				</tr>
			</Table>
		</form>	
EOD;
}

	if ( preg_replace("/[^a-zA-Z0-9\s]/", "", $_POST['msg']) == $_POST['msg'] )
// the above statement says if pass contains no special characters
{
	$query = "INSERT INTO contact(name,email,msg) VALUES ('$v_name','$v_email','$v_msg')";
	$result = mysql_query( $query );

	if( !$result ) {
		die( mysql_error() );
	}
	echo <<<EOD
		<head>      
			<link rel="stylesheet" type="text/css" href="http://hedgezoo.com/signup.css">
		</head>
		<h2>Free Registration</h2>
		<form action="contact_insert2.php" method="POST" id="insert">
			<table>
				<tr>
					<td>Email</td>
					<td ><input type="text" size="40" name="name"></td>
				</tr>
			    <tr>
					<td>Password</td>
					<td><input type="password" size="40"  name="msg" ></td>
				</tr>
				<tr>
					<td colspan=2 id="sub">
						<div style="color:red;">Your password must have at least one special character.</div> <br />
						<input type="submit" name="submit" value="submit">
					</td>
				</tr>
			</Table>
		</form>	
EOD;
}
else 
echo <<<EOD
<B>GO FUCK YOURSELF</B>
EOD;
 ?>

Link to comment
Share on other sites

Before you worry about redisplaying the entered values in the form, you need to fix the logic on that page. You are repeating your form code 6 times.

 

You should only have the form code present ONCE, near the end, after you have validated the form data.

 

You should only display the form if the page was browsed to (not a form submission) or if there are any validation errors.

 

Here is the general logic needed -

// Form/form processing pseudo code

// form processing code
if(form_submitted){

condition and validate form data

if(no form_errors){
	// use form data
}
}

// form code
if(form_not_submitted OR form_errors){
if(form_errors){
	display form errors
}
display form with existing field values (if present)
}

Link to comment
Share on other sites

set the value to a if statement that looks to see if that input field has been stored; if so, echo the stored data :)

<label for="price">Price:</label>$
      <input type="text" name="price" value="<?php if (!empty($price)) echo $price; ?>" />

 

hope this helps

Link to comment
Share on other sites

Also I recommend strongly removing your database, username and password details from any code you post to the site, as you have just given the world access to your system posting them here, would be a good idea to change your db password now aswell.

Link to comment
Share on other sites

Also I recommend strongly removing your database, username and password details from any code you post to the site, as you have just given the world access to your system posting them here, would be a good idea to change your db password now aswell.

 

yeah i just noticed that, dumb. I just changed the pw.

Link to comment
Share on other sites

Before you worry about redisplaying the entered values in the form, you need to fix the logic on that page. You are repeating your form code 6 times.

 

You should only have the form code present ONCE, near the end, after you have validated the form data.

 

You should only display the form if the page was browsed to (not a form submission) or if there are any validation errors.

 

Here is the general logic needed -

// Form/form processing pseudo code

// form processing code
if(form_submitted){

condition and validate form data

if(no form_errors){
	// use form data
}
}

// form code
if(form_not_submitted OR form_errors){
if(form_errors){
	display form errors
}
display form with existing field values (if present)
}

 

 

I noticed that problem as well, I don't really understand your code, is it possible to just put a break; or something at the end of each individual if?

Link to comment
Share on other sites

I have looked at your logic more, and it is not even doing what you expect. For each validation test, some with conditions that are backwards from what you probably intended, you are executing the INSERT query.

 

In the pseudo code I posted, you would only execute the query where the // use form data comment is.

Link to comment
Share on other sites

something like this simple example

 

<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {

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

// check for errors here, examples
if ($name=='') $aError['name'] = 'Missing Name';
if ($email=='') $aError['email'] = 'Missing Email';
if ($msg=='') $aError['msg'] = 'Missing Message';

// no errors process form
if (count($aError) == 0) {
// --process form here--

} else {

// put errors into a variable
$strError="<div><ul>";
foreach ($aError as $error) {
$strError .= "<li>$error</li>";
}
$strError.="</ul></div>"
}

//print the errors encountered
echo $strError
?>

Put your form here in the html

 

I also noticed you dont seem to have an email field in your form inputs you have the name email but only a name and msg field.

Link to comment
Share on other sites

dragon, I tried your template...

 

but I am getting an error

 

Parse error: syntax error, unexpected '}' in /hermes/bosweb25c/b1454/ipg.site/site/contact_insert2.php on line 91

 

Line 91 is 7 lines up from the very bottom, I commented where it is. Not sure what is happening here.

 

 <?php

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;
}

define('DB_NAME', 'dbname');
define('DB_USER', 'username');
define('DB_PASS', 'password');
define('DB_HOST', 'page.sqlserver.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 data in local variable
$v_name=$_POST['name'];
$v_email=$_POST['email'];
$v_msg=$_POST['msg'];



if ($_SERVER['REQUEST_METHOD']=='POST') {

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

// check for errors here, examples
if (check_email_address($_POST['name'])  == false)

	$aError['name'] = 'Invalid Email';   

if (  $v_name == "" || $v_msg == "" )

	$aError['msg'] = 'Missing Email and Password';

if (  strcspn( $_REQUEST['msg'], '0123456789' ) == strlen( $_REQUEST['msg'] )   )

	$aError['msg'] = 'Missing a Number';

if (  strlen($_POST['msg']) < 8  )

		$aError['msg'] = 'Less than 8 characters';

if (     $_POST['msg'] == strtolower($_POST['msg'])    )

		$aError['msg'] = 'All lower case';

if ( preg_replace("/[^a-zA-Z0-9\s]/", "", $_POST['msg']) == $_POST['msg']  )

		$aError['msg'] = 'Need one special characetr';

// no errors process form
if (count($aError) == 0) {
// --process form here--

} else {

// put errors into a variable
$strError="<div><ul>";
foreach ($aError as $error) {
$strError .= "<li>$error</li>";
}
$strError.="</ul></div>"
}       // this is line 91

//print the errors encountered
echo $strError
?>

Put your form here in the html






Link to comment
Share on other sites

also you have $aError['msg'] many times each error needs to have a unique identifier eg $aError['msg'], $aError['msg1'], $aError['msg2'] and so on, that is the key for the error messages and the count at the end

Link to comment
Share on other sites

Here is a full working example of a user registration script. The only part missing is your "strong password check" functionality. This is just an example though it has been tested.

 

<?php

/*
	Written By: SMS Marketeers
	Website: http://www.smsmarketeers.com

	User registration with error checking and reporting.

	Database Structure

	CREATE TABLE IF NOT EXISTS `user` (
	`user_id` int(11) NOT NULL AUTO_INCREMENT,
	`firstname` varchar(32) CHARACTER SET latin1 NOT NULL,
	`lastname` varchar(32) CHARACTER SET latin1 NOT NULL,
	`email` varchar(96) CHARACTER SET latin1 NOT NULL,
	`username` varchar(32) CHARACTER SET latin1 NOT NULL,
	`password` varchar(32) CHARACTER SET latin1 NOT NULL,
	`date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
	PRIMARY KEY (`user_id`)
	) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=1 ;
*/

// Define Database Variables
$dbHostname = 'localhost';
$dbUsername = 'username';
$dbPassword = 'password';
$dbDatabase = 'database';

// Establish Database Connection
$dbCon = mysql_connect($dbHostname, $dbUsername, $dbPassword) or die('Error: Unable able to connect: ' . mysql_error());

// Select Working Database
$dbSel = mysql_select_db($dbDatabase, $dbCon) or die('Error: Unable to select database: ' . mysql_error());

// Handle POST
$error = array();
$showForm = true;

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	$emailPattern = '/^[A-Z0-9._%\-+]+@[A-Z0-9][A-Z0-9.-]{0,61}[A-Z0-9]\.[A-Z]{2,6}$/i';

	// Validate fields first
	if (empty($_POST['firstname'])) {
		$error['firstname'] = '<strong>Error:</strong> First Name is a required field!';
	}

	if (empty($_POST['lastname'])) {
		$error['lastname'] = '<strong>Error:</strong> Last Name is a required field!';
	}

	if (empty($_POST['email']) || (!preg_match($emailPattern, $_POST['email']))) {
		$error['email'] = '<strong>Error:</strong> Either the email address was left blank or is not valid!';
	}

	if (empty($_POST['username'])) {
		$error['username'] = '<strong>Error:</strong> Username is a required field!';
	}

	if (empty($_POST['password'])) {
		$error['password'] = '<strong>Error:</strong> Password is a required field!';
	}

	if (empty($_POST['confirm']) || $_POST['confirm'] != $_POST['password']) {
		$error['confirm'] = '<strong>Error:</strong> Confirm is a required field and must match password!';
	}

    	if (!$error) {
		mysql_query("INSERT INTO user SET firstname = '" . $_POST['firstname'] . "', lastname = '" . $_POST['lastname'] . "', email = '" . $_POST['email'] . "', username = '" . $_POST['username'] . "', password = '" . md5($_POST['password']) . "', date = NOW()") or die('Error: Unable to execute query: ' . mysql_error());
		$showForm = false;
    	} else {
		$showForm = true;
	}
}

// Setup input variables
if ($_POST['firstname']) {
	$firstname = $_POST['firstname'];
} else {
	$firstname = '';
}

if ($_POST['lastname']) {
	$lastname = $_POST['lastname'];
} else {
	$lastname = '';
}

if ($_POST['email']) {
	$email = $_POST['email'];
} else {
	$email = '';
}

if ($_POST['username']) {
	$username = $_POST['username'];
} else {
	$username = '';
}

?>

<html>
<head>
<title>User Registration</title>
<style type="text/css">
	*		{ font-size:12px; font-family:Arial; margin:0px; outline:0px; padding:0px; }
	body	{ background:#ffffff; color:#000000; margin:10px 0px 0px 0px; }
	img		{ border:0px; }
	p		{ margin:5px 0px 10px 0px; }
	form	{ border:none; margin:0px; padding:0px; }

	a				{ cursor:pointer; }
	a:link			{ color:#9AB324; text-decoration:none; }
	a:visited		{ color:#9AB324; text-decoration:none; }
	a:hover 		{ color:#9AB324; text-decoration:underline; }
	a:active 		{ color:#9AB324; text-decoration:none; }

	.container		{ margin:0px auto; width:700px; }
	.success		{ background:#EEF5CD; border:1px dashed #9AB324; color:#608339; margin-bottom:5px; padding:5px; text-align:left; }
	.warning		{ background:#eed4d2; border:1px dashed #a94637; color:#ac241a; margin-bottom:5px; padding:5px; text-align:left; }
	.attention		{ background:#fefbcc; border:1px dashed #e6db55; color:#ada019; margin-bottom:5px; padding:5px; text-align:left; }

	form, fieldset			{ border:none; margin:0px; padding:0px; }
	input, textarea, select { font:100% arial, sans-serif; vertical-align:middle; }
	input[type='text']		{ background:#ffffff; border:1px solid #c3c3c3; border-left-color:#7c7c7c; border-top-color:#7c7c7c; padding:2px; }
	input[type='password']	{ background:#ffffff; border:1px solid #c3c3c3; border-left-color:#7c7c7c; border-top-color:#7c7c7c; padding:2px; }
	input[type='radio']		{ margin:0px 5px 0px 5px; }
	input[type='hidden']	{ display:none !important; }
	select					{ border:1px solid #c3c3c3; border-left-color:#7c7c7c; border-top-color:#7c7c7c; min-width:100px; padding:1px; }
	select option			{ padding:0px 5px 0px 5px; }
	textarea				{ background:#ffffff; border:1px solid #c3c3c3; border-left-color:#7c7c7c; border-top-color:#7c7c7c; padding:2px; }

	table.form th				{ background:#9AB324; border-bottom:1px solid #596E0E; color:#ffffff; font-weight:bold; padding:5px; text-align:center; }
	table.form td				{ padding:5px; }
	table.form td.colOne		{ background:#f0f0f0; border-bottom:1px solid #dddddd; }
	table.form td.colTwo		{ background:#f5f5f5; border-bottom:1px solid #dddddd; }
	table.form td.button		{ background:#ffffff; border:none; text-align:right; }
</style>
</head>
<body>

<div class="container">
<?php if ($showForm == true) { ?>
	<form action="" method="POST" name="form" id="form">
		<div class="attention">This is an example for user registration with error checking and reporting.</div>

		<table align="center" border="0px" cellpadding="0px" cellspacing="1px" class="form" width="700px">
			<tr>
				<td class="colOne" width="150px">First Name:</td>
				<td class="colTwo">
					<input name="firstname" type="text" value="<?php echo $firstname; ?>" />
					<?php if ($error['firstname']) { ?><span class="warning"><?php echo $error['firstname']; ?></span><?php } ?>
				</td>
			</tr>
			<tr>
				<td class="colOne">Last Name:</td>
				<td class="colTwo">
					<input name="lastname" type="text" value="<?php echo $lastname; ?>" />
					<?php if ($error['lastname']) { ?><span class="warning"><?php echo $error['lastname']; ?></span><?php } ?>
				</td>
			</tr>
			<tr>
				<td class="colOne">Email Address:</td>
				<td class="colTwo">
					<input name="email" type="text" value="<?php echo $email; ?>" />
					<?php if ($error['email']) { ?><span class="warning"><?php echo $error['email']; ?></span><?php } ?>
				</td>
			</tr>
			<tr>
				<td class="colOne">Username:</td>
				<td class="colTwo">
					<input name="username" type="text" value="<?php echo $username; ?>" />
					<?php if ($error['username']) { ?><span class="warning"><?php echo $error['username']; ?></span><?php } ?>
				</td>
			</tr>
			<tr>
				<td class="colOne">Password:</td>
				<td class="colTwo">
					<input name="password" type="password" value="" />
					<?php if ($error['password']) { ?><span class="warning"><?php echo $error['password']; ?></span><?php } ?>
				</td>
			</tr>
			<tr>
				<td class="colOne">Confirm Password:</td>
				<td class="colTwo">
					<input name="confirm" type="password" value="" />
					<?php if ($error['confirm']) { ?><span class="warning"><?php echo $error['confirm']; ?></span><?php } ?>
				</td>
			</tr>
			<tr><td class="button" colspan="4"><input name="submit" type="submit" value="Create Profile" /></td></tr>
		</table>
	</form>
<?php } elseif ($showForm == false) { ?>
	<div class="success">Thank you for your registration.</div>
<?php } ?>
</div>

<?php mysql_close($link); ?>

</body>
</html>

Link to comment
Share on other sites

I just figured it out dragon. It looks great.

 

Now I just have to create the screens that will show whenever those conditions are met.

 

If we do it via your script its possible correct?

 

I want to show one error message at a time. So if a person types in

 

'envision' as the password

 

I want it to show only "You need a number"

 

Then the person would type

 

'envision2'

 

and I want to make it show "you need at least one capital letter" etc.

Link to comment
Share on other sites

at the moment it is set to show all the errors that dont meet your if statements, as the user fixes them it will remove each error message, usually its a good idea to display like this otherwise the user can be frustrated having to fix so many errors if they only learn about them one at a time.

If you do want to show them one at a time then just remove the bit at the bottom of the script ($strError part) and replace that with if statements pertaining to each error should it arise from the users input.

Link to comment
Share on other sites

I wasn't sure how you do in if statement on an array like that so I thought a while would work just as well.

 

I thought the logic would be, while $c is less than 1, print the array using what you wrote dragon.

 

but then I added $c++ to make it add one each time. So I thought it would add 1 after printing the first error message and then stop.

 

But it doesn't seem to be working that way.

 

 

// put errors into a variable
$strError="<div><ul>";
$c=0;
while ( $c < 1 )
foreach ($aError as $error) {
$strError .= "<li>$error</li>";
$c++;
}
$strError.="</ul></div>";

Link to comment
Share on other sites

Also for that to work you need to change the array variable for each error to this

 

$aError[]

 

so $aError['msg'] would become $aError[]

and $aError['msg1'] would become $aError[]

and $aError['email'] would become $aError[]

and so on for all your error rules

 

this way each time you use $aError[] it will add the error message to that array and it will number them 0,1,2,3 etc by default, which is why you echo $aError[0] for 1 message at a time and it will always be the first error encountered as it goes through your validation rules.

Link to comment
Share on other sites

Yup, thats exactly what I'm doing and the program works now:)

 

Now I am trying to figure out how to prepopulate it with what the user entered (the point of original thread).

 

I can't seem to get it working. In the error processing part of the script, I'm simply echoing the html.

 

I'm trying to echo the latest entry in the db and set it as the value for the forms. but when I echo $data2[name], nothing happens?

 

 

echo "
<head>
<?php 

$connection = mysql_connect('sqlserver','user','pass') or die (\"Couldn't connect to server.\");  
$db = mysql_select_db('dbname', $connection) or die (\"Couldn't select database.\");  

$data = 'SELECT * 
FROM contact
ORDER BY TIMESTAMP DESC 
LIMIT 1'; 
  $query = mysql_query($data) or die(\"Couldn't execute query. \". mysql_error()); 
  $data2 = mysql_fetch_array($query); 
   
   
?> 
</head>

  <link rel=\"stylesheet\" type=\"text/css\" href=\"http://site.com/signup.css\">


<!--  BEGIN CENTER -->
<div class=\"center\">
      <h1>Join free:</h1>
      <form action=\"contact_insert2.php\" method=\"POST\" id=\"insert\">                        
                                          <div class=\"labels\">Email Address</div>
                                         <input type=\"text\" size=28 name=\"name\" value=\"$data2[name]\">
                                          <div class=\"labels\">Choose Password</div>
                                         <input type=\"password\" size=28  name=\"msg\" >
									 <div class=\"error\">$aError[0]</div>
				$data2[name]
									 	 <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><br><br><br>
      </form>
  </div></div>
<!--  BEGIN RIGHT -->

  
  
  </div>"

Link to comment
Share on other sites

Why do we need an if?

 

I just want to put the last entry of pass and email into the form. It sounds simple enough?

 

<?php

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;
}

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 data in local variable
$v_name=$_POST['name'];
$v_email=$_POST['email'];
$v_msg=$_POST['msg'];



if ($_SERVER['REQUEST_METHOD']=='POST') {

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

// check for errors here, examples





if (  strlen($_POST['msg']) < 8  )

		$aError['0'] = 'Password must be at least 8 characters.';

if (     $_POST['msg'] == strtolower($_POST['msg'])    )

		$aError['0'] = 'Password must have at least 1 uppercase.';

if ( preg_replace("/[^a-zA-Z0-9\s]/", "", $_POST['msg']) == $_POST['msg']  )

		$aError['0'] = 'Password must have a least one special character.';

if (  strcspn( $_REQUEST['msg'], '0123456789' ) == strlen( $_REQUEST['msg'] )   )

	$aError['0'] = 'Password must one at least one number.';

if (  $v_name == "" || $v_msg == "" )

	$aError['0'] = 'Please enter a password.';

if (check_email_address($_POST['name'])  == false)

	$aError['0'] = '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 ('$v_name','$v_email','$v_msg')";
	$result = mysql_query( $query );

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



}
// YES THERE ARE ERRORS
else {


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

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




// put errors into a variable

//$strError="<div><ul>";
//foreach ($aError as $error) {
//$strError .= "<li>$error</li>";
//}
//$strError.="</ul></div>";



}
}
//print the errors encountered


echo "
<head>
<?php 

$connection = mysql_connect('server.sql.com','username','pass') or die (\"Couldn't connect to server.\");  
$db = mysql_select_db('catch', $connection) or die (\"Couldn't select database.\");  

$data = 'SELECT * 
FROM contact
ORDER BY TIMESTAMP DESC 
LIMIT 1'; 
  $query = mysql_query($data) or die(\"Couldn't execute query. \". mysql_error()); 
  $data2 = mysql_fetch_array($query); 
   
   
?> 
</head

  <link rel=\"stylesheet\" type=\"text/css\" href=\"http://site.com/signup.css\">
<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=\"contact_insert2.php\" method=\"POST\" id=\"insert\">                        
                                          <div class=\"labels\">Email Address</div>
                                         <input type=\"text\" size=28 name=\"name\" value=\"$data2[name]\">
                                          <div class=\"labels\">Choose Password</div>
                                         <input type=\"password\" size=28  name=\"msg\" >
									 <div class=\"error\">$aError[0]</div>
				$data2[name]
									 	 <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><br><br><br>
      </form>
  </div></div>
<!--  BEGIN RIGHT -->

  
  
  </div>"

?>










Link to comment
Share on other sites

give this a try

 

<?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')";
	$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>

<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($aError[0]) && $aError[0]!="") { 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>
</body>
</html>

Link to comment
Share on other sites

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.