Jump to content

Recommended Posts

Hello, I'm new here and I registered because I am a PHP newbie and I am trying to build a website. I have constructed a form and a validator for the form, but I want to highlight the names of the fields with improper input. I have tried several different ways and this version is the closest I've gotten. Assuming the user has submitted a form with errors I create a string containing the names of all the fields with errors and then store it in a session. Then when the page reloads it is supposed to change the class names of the fields with errors highlighted red.

 

<?php 
session_start();
$_SESSION['vars'];
?>
<!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>Sign Up Form</title>
<script type="text/javascript" src="country.js"></script>
<style type="text/css">label.error {color:#ff0000}</style>
</head>
<body>

<?php

// connect_db() is a funtion that will connect with the server and display error messages when it cannot connect
function connect_db()
{
	include('db_login.php'); // db_login contains the connection details
	$db_handle = mysql_connect($server,$username,$password);

	if(!db_handle) // Cannot connect
	{
		print die('Could not establish connection with database.<br />' . mysql_error());
	}
	else // Does connect
	{
		print $db_handle . " Connection to database successfully established.\n";		
		$db_found = mysql_select_db($database);
	}
}

// write_user_data() will both validate and post user data to the database
function write_user_data()
{				
	// Make form data global variables by placing outside any function
	$user_intention = mysql_real_escape_string($_POST[user_intention]);
	$title = mysql_real_escape_string($_POST[title]);
	$first_name = mysql_real_escape_string($_POST[first_name]);
	$last_name = mysql_real_escape_string($_POST[last_name]);
	$password = mysql_real_escape_string($_POST[password]);
	$password1 = mysql_real_escape_string($_POST[password1]);
	$phone1 = mysql_real_escape_string($_POST[phone1]);
	$email1 = mysql_real_escape_string($_POST[email1]);
	$email2 = mysql_real_escape_string($_POST[email2]);
	$user_website = mysql_real_escape_string($_POST[user_website]);
	$country = mysql_real_escape_string($_POST[country]);
	$state = mysql_real_escape_string($_POST[state]);	
	$full_name = "$first_name $last_name";		

// VALIDATE FORM DATA

$form_errors; // Stores the HTML name of all fields with errors(run through real_escape before output)

// EMAIL	
if ((preg_match('/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\@([a-z0-9])' .
'(([a-z0-9-])*([a-z0-9]))+' . '(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i',$email1) === 0) || (empty($email1)))
{
	$form_errors = "email1%";
}
if (strcmp($email1,$email2) != 0)
{
	$form_errors .= "email2%";
}

// PASSWORD
// Password must be at least 1 and not more than 15 characters long and only contain letters and numbers
if ((preg_match('/[[:alnum:]]/i',$password) === 0) || (empty($password)))
{
	$form_errors .= "password%";
}
if (strcmp($password,$password1) != 0)
{
	$form_errors .= "password1%";	
}

// NAMES
if ((preg_match('/a-z/i',$first_name) != 0) || (empty($first_name)))
{
	$form_errors .= "first_name%";
}
if ((preg_match('/a-z/i',$last_name) != 0) || (empty($last_name)))
{
	$form_errors .= "last_name%";
}	

// Reprint form with CSS classes relabeled to error
// Does the form have errors?
if (!empty($form_errors))
{
	print "Attempting to register variables in session array:<br />";
	echo ('$form_errors') . " = " . $form_errors . "<br />";
	$_SESSION['vars'] = $form_errors;
	print_r($_SESSION['vars']);
}
else
{		
	// Set what is to be sent
	$query = "INSERT INTO user  (id,user_intention,title,first_name,last_name,password,phone1,email1,user_website,country,state) 
	VALUES 

('','$user_intention','$title','$first_name','$last_name','$password','$phone1','$email1','$user_website','$country','$state')";

	if (!mysql_query($query))
	{
		die('Error: ' . mysql_error()); 
	} 
	print $full_name . " was successfully added to your database.<br />";
}
}

if ($_POST['process'] === '1')
{
print "Process = 1";
connect_db(); 
write_user_data();
}
else
{
print "Process = 0";
}
?>

<form action="signup1.php" method="POST">
<table width="98%" border="0">
  <tr>
    <td>
    Complete the form below to sign up.
    </td>
  </tr>
  <tr>
    <td>
    <label>
    <b>Are you an: </b>
    <select name="user_intention">
    	<option>Investor</option>
        <option>Entrepreneur</option>
        <option>Both</option>
    </select> 
    </label>
    </td>
  </tr>
  <tr>
    <td>
    <label>
    	<b>Title: </b>
        	<select name="title">
            	<option>Mr</option>
                <option>Ms</option>
                <option>Mrs</option>
            </select>
    </label>
    </td>
  </tr>
  <tr>
    <td>
    <label class=<?php if(strpbrk($_SESSION['vars'],"first_name%") != false){ echo ('"first_name"'); } else { echo ('"error"'); } ?>>    	
        <b>First Name: </b><input type="text" name="first_name" />
    </label>
    <label  class="last_name">    
            <b>Last Name: </b><input type="text" name="last_name" />
    </label>
    </td>
  </tr>
  <tr>
    <td>
    <label class="password">
        <b>Password: </b><input type="text" maxlength="15" name="password" />
    </label>
    <label class="password1">    
            <b>Confirm Password: </b><input type="text" maxlength="15" name="password1" /><br />
        Your password may be upto 15 characters in length and may contain only letters and numbers.
    </label>
    </td>
  </tr>  
  <tr>
    <td>
    <label>
    	<b>Phone Number: </b><input type="text" name="phone1" />
    </label>
    </td>
  </tr>
  <tr>
    <td>
    <label class = "email1">
        <b>Email :</b><input type="text" name="email1" />
    </label>
    <label class="email2">    
            <b>Confirm Email :</b><input type="text" name="email2" />
    </label>
    </td>

  </tr>
  <tr>
    <td>
    <label>
    	<b>Website URL: </b><input type="text" name="user_website" />
    </label>
    </td>
  </tr>
  </tr>
  <tr>
    <td>
    <label>
    	<b>Country: </b><select id='countrySelect' name='country' onchange='populateState()'></select>
        					<select id='stateSelect' name='state'></select>
        					<script type="text/javascript">initCountry('US');</script>
    </label>
    </td>
  </tr> 
  <tr>
  	<td>
<input type="hidden" name="process" value="1">
    <input type="submit" value="Go!" />
    </td>
  </tr> 
</table>
</form>

</body>
</html>

 

I pasted the code in its entirety because I think the problem may be that PHP does parse the way I think it does. If anyone can see anything obviously wrong with the code please tell me. All critiques are welcome but please be nice :)

Link to comment
https://forums.phpfreaks.com/topic/153916-php-within-html-tags/
Share on other sites

You have a couple problems.

 

1) Your submit button doesn't have a name.

2) You're calling the functions to do the actual work when:

 

if ($_POST['process'] === '1')

 

which never happens.

 

Try this, replace all of this:

 

if ($_POST['process'] === '1')
{
   print "Process = 1";
   connect_db(); 
   write_user_data();
}
else
{
   print "Process = 0";
}

 

with:

 

if(isset($_POST['submit']))
{
   print "Process = 1";
   connect_db(); 
   write_user_data();
}

 

And replace:

 

    

 

with this:

 

    

 

 

Now when the user clicks "Go!", which is the same as isset($_POST['submit']), it will call all of your functions that process your information.

Link to comment
https://forums.phpfreaks.com/topic/153916-php-within-html-tags/#findComment-809096
Share on other sites

Thank you very much for replying. Even though your response didn't get the form changing colors, I appreciate your help with my misunderstanding of my program's flow. I replaced my code with what you supplied but the PHP code within the class tag in the form labeled first_name does not seem to change when the form is submitted with improper information. I will continue to work on it, but again any help is appreciated. Thank you.

Link to comment
https://forums.phpfreaks.com/topic/153916-php-within-html-tags/#findComment-809155
Share on other sites

Sorry, let me explain. When the user arrives at signup1.php it will display the sign-up form. They fill it out and press submit. The form is submitted to itself and checked for errors. The script goes through the data entered into each form input box and determines if it is a valid entry or not. If it is not I would like it to change the color of the text of the name beside the input box to red.

if ((preg_match('/a-z/i',$first_name) != 0) || (empty($first_name)))
{
	$form_errors .= "first_name%";
}

$form_errors is a string that holds the names of the input boxes with errors separated by a %. Later on...

<tr>
    <td>
    <label class=<?php if(strpbrk($_SESSION['vars'],"first_name%") != false){ echo ('"first_name"'); } else { echo ('"error"'); } ?>>    	
        <b>First Name: </b><input type="text" name="first_name" />
    </label>

Before the class of the input box is printed I want to search the $form_errors string for 'first_name%.' But the color never seems to change. I don't understand why.

Link to comment
https://forums.phpfreaks.com/topic/153916-php-within-html-tags/#findComment-809184
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.