simple form validation help needed. [solved]

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
lafflin
Forum Contributor
Posts: 123
Joined: Thu Jul 26, 2007 6:26 pm

simple form validation help needed. [solved]

Post by lafflin »

Hello, I am having trouble with some very simple code that I wrote to validate a form used to enter students into a database. This Issue only pertains to the PHP. The field on my form that I'm having trouble with is the 'months' field. The only validation I'm using is to ensure that it's not empty, but the field itself is a drop down date menu created with a for each loop and the months as an array. (i'm a newb, but I'm sure you've seen this) To validate the date I only check to ensure month is not empty, and to do that I had to add a blank space in my months array to represent what would be set if the user filling out the form never choose a month. But the issue is that I can leave it blank and still enter my form with no error. any help would be greatly appreciated.

In case anyone is wondering why there is no security in this code, it's because I'm a newb, this is my first project, and I am doing this in layers so to speak, meaning that I need to get this basic code working before I can start adding security.

Code: Select all

<?php # - register.php -

$page_title = 'Register';
include ('./includes/header.inc.htm');

// Check if the form has been submitted.
if (isset($_POST['submitted'])) {

	$errors = array(); // Initialize error array.
	
	// Check for a first name.
	if (empty($_POST['first_name'])) {
		$errors[] = 'You forgot to enter your first name.';
	} else {
		$fn = trim($_POST['first_name']);
	}
	
	// Check for a last name.
	if (empty($_POST['last_name'])) {
		$errors[] = 'You forgot to enter your last name.';
	} else {
		$ln = trim($_POST['last_name']);
	}
	
	// Check for a date of birth.
	if (empty($_POST['month'])) {
		$errors[] = 'You forgot to enter students birthdate.';
	} else {
		$dob = trim($_POST['year']).($_POST['month']).($_POST['day']);
	}
	
	// Check for a last name.
	if (empty($_POST['sex'])) {
		$errors[] = 'You forgot to enter students sex.';
	} else {
		$sex = trim($_POST['sex']);
	}
	
	//following fields not mandatory
	
	// Check for a school attending.
	if (empty($_POST['school'])) {
		$school ='null';
	} else {
		$school = trim($_POST['school']);
	}
	
	// Check for a medical issues.
	if (empty($_POST['medical'])) {
		$medical ='null';
	} else {
		$medical = trim($_POST['medical']);
	}
	
	// Check for a students phone.
	if (empty($_POST['students_phone'])) {
		$stud_phon ='null';
	} else {
		$stud_phon = trim($_POST['students_phone']);
	}
	
	// Check for a students email.
	if (empty($_POST['student_email'])) {
		$stud_email ='null';
	} else {
		$stud_email = trim($_POST['stud_email']);
	}
	
	// Check for notes.
	if (empty($_POST['notes'])) {
		$notes ='null';
	} else {
		$notes = trim($_POST['notes']);
	}
	if (empty($errors)) { // If everything's okay.
	
		// Register the user in the database.
		require_once ('./includes/mysql_connect.php'); // Connect to the db.
		
		// Make the query.
		$query = "INSERT INTO student_info (sid, first_name, last_name, sex, reg_date, dob, school, email, phone, active, medical_issues, notes, secret_classification, last_update) VALUES ('null', '$fn', '$ln', '$sex', now(), '$dob', '$school', '$stud_email', '$stud_phone', 'y', '$medical', '$notes', '0', 'null' )";		
		$result = @mysql_query ($query); // Run the query.
		if ($result) { // If it ran OK.
		
			// Send an email, if desired.
			
			// Print a message.
			echo '<h1 id="mainhead">Thank you!</h1>
		<p>You are now registered. In Chapter 9 you will actually be able to log in!</p><p><br /></p>';	
		
			// Include the footer and quit the script (to not show the form).
			//include ('./includes/footer.htm'); 
			
			exit();
			
		} else { // If it did not run OK.
			echo '<h1 id="mainhead">System Error</h1>
			<p class="error">You could not be registered due to a system error. We apologize for any inconvenience.</p>'; // Public message.
			echo '<p>' . mysql_error() . '<br /><br />Query: ' . $query . '</p>'; // Debugging message.
			include ('./includes/footer.inc.htm'); 
			exit();
		}
		
		mysql_close(); // Close the database connection.
		
	} else { // Report the errors.
	
		echo '<h1 id="mainhead">Error!</h1>
		<p class="error">The following error(s) occurred:<br />';
		foreach ($errors as $msg) { // Print each error.
			echo " - $msg<br />\n";
		}
		echo '</p><p>Please try again.</p><p><br /></p>';
		
	} // End of if (empty($errors)) IF.

} // End of the main Submit conditional.
?>


<table width="700" height="604" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td width="46" height="26">&nbsp;</td>
    <td width="620">&nbsp;</td>
    <td width="34">&nbsp;</td>
  </tr>
  <tr>
    <td height="493">&nbsp;</td>
    <td><form id="form1" name="form1" method="post" action="">
      <table width="700" height="176" border="0" cellpadding="0" cellspacing="0">
        <tr>
          <td width="224"><label for="textfield">First Name</label>
            <input type="text" name="first_name" accesskey="f" tabindex="1" id="textfield" /></td>
          <td width="230"><label for="label">Last Name</label>
            <input type="text" name="last_name" accesskey="l" tabindex="2" id="label" /></td>
          <td width="246">
		  Date of Birth<br/> 
		  <?php # Script 2.7 - calendar.php
// This script makes three pull-down menus for an HTML form: months, days, years.

// Make the months array.
$months = array (1 => '','January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');

// Make the days and years arrays.
$days = range (1, 31);
$years = range (1975, 2005);

// Make the months pull-down menu.
echo '<select name="month">';
foreach ($months as $key => $value) {
	echo "<option value=\"$key\">$value</option>\n";
}
echo '</select>';

// Make the days pull-down menu.
echo '<select name="day">';
foreach ($days as $value) {
	echo "<option value=\"$value\">$value</option>\n";
}
echo '</select>';

// Make the years pull-down menu.
echo '<select name="year">';
foreach ($years as $value) {
	echo "<option value=\"$value\">$value</option>\n";
}
echo '</select>';

?><br/></td>
        </tr>
        <tr>
          <td><p><br/>
            <label>
              <input type="radio" name="sex" value="f" />
              Female</label>
            <br />
            <label>
              <input type="radio" name="sex" value="m" />
              Male</label>
            <br />
          </p></td>
          <td>
		  <br/>
		  <label for="label2">School</label>
		  <br/>
		  <input type="text" name="school" accesskey="o" tabindex="5" id="label2" />
			<br>
			<span class="note">For students in k-12</span></td>
          <td>
		  <br/>
		  <label for="textarea">Known medical issues / Instructions</label>
		
		  <textarea name="medical" cols="35" id="textarea" accesskey="m" tabindex="6"></textarea>
            </td>
        </tr>
        <tr>
          <td height="76"><label for="label3">Students phone </label>
            <input type="text" name="student_phone" accesskey="p" tabindex="8" id="label3" /></td>
          <td><label for="label4">Students email</label>
            <input type="text" name="student_email" accesskey="e" tabindex="9" id="label4" /></td>
          <td><label for="label5">Notes</label>
            <textarea name="notes" cols="35" id="label5" accesskey="n" tabindex="10"></textarea></td>
        </tr>
      </table>
      <label for="textfield"></label>
      <p>
	  <div align="center">
        <label for="Submit"></label>
        <input type="submit" name="Submit" value="Submit" accesskey="z" id="Submit" />
        <br />
	    <input type="hidden" name="submitted" />
	    </p>
		</div>
	  
	  
	  
    </form>
    
    </td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
</table>
</body>
</html>
Last edited by lafflin on Tue Aug 14, 2007 9:48 am, edited 1 time in total.
SidewinderX
Forum Contributor
Posts: 407
Joined: Fri Jul 16, 2004 9:04 pm
Location: NY

Post by SidewinderX »

Well as far as I'm concerned, a blank space is not 'empty' [although I do find php to be weird when it comes something being nothing].

Code: Select all

// Check for a date of birth.
        if ($_POST['month'] != " ") {
                $errors[] = 'You forgot to enter students birthdate.';
        } else {
                $dob = trim($_POST['year']).($_POST['month']).($_POST['day']);
        }
Seems to make more sense - or I could be way off.
lafflin
Forum Contributor
Posts: 123
Joined: Thu Jul 26, 2007 6:26 pm

Post by lafflin »

Okay, I think I figured it out, I'm embarassed that I couldn't see this before. Having a blank space is not empty, and that is the issue. So the obvious thing to do is to is:

Code: Select all

if ($_POST['month'] = " ") { 
                $errors[] = 'You forgot to enter students birthdate.'; 
        } else { 
                $dob = trim($_POST['year']).($_POST['month']).($_POST['day']); 
        }
I believe that you were right on sidewinder, but your logic was backwards, if "month" value is a blank space then I want the error. However I may look at this again in five minutes and realize that my head was on backwards. Still Your post was helpful and it is appreciated.
SidewinderX
Forum Contributor
Posts: 407
Joined: Fri Jul 16, 2004 9:04 pm
Location: NY

Post by SidewinderX »

Glad I could help. :D
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

lafflin wrote:

Code: Select all

if ($_POST['month'] = " ") {
Umm....
I hope you see what I see.

I've no idea what this thread is in regards to, but firstly, why would you check against a blank space? And secondly, '=' is not '=='.
lafflin
Forum Contributor
Posts: 123
Joined: Thu Jul 26, 2007 6:26 pm

Post by lafflin »

Whoops, right I forgot my second "=" . I'm a bit confused though, did I not post that reply in this thread or something?
The reason I would check against a blank space is because the default value of my drop down menu is a blank space, and if the form is submitted with a blank space as the value than an error will be displayed. But then again this is my first project and I'm kinda teaching myself so if there's a better way to do this please do share.

If yours is a lightsaber than grace the Padawan with your insight.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

lafflin wrote:Whoops, right I forgot my second "=" . I'm a bit confused though, did I not post that reply in this thread or something?
The reason I would check against a blank space is because the default value of my drop down menu is a blank space, and if the form is submitted with a blank space as the value than an error will be displayed. But then again this is my first project and I'm kinda teaching myself so if there's a better way to do this please do share.

If yours is a lightsaber than grace the Padawan with your insight.
Make the default value empty, and use empty(). Also, get into the habit of using trim() as well on user input.

Code: Select all

<select>
    <option value="">-- Make a selection --</option>
    <option value="foo">Foo!</option>
    <option value="bar">Bar...</option>
</select>
Makes a lot more sense.
lafflin
Forum Contributor
Posts: 123
Joined: Thu Jul 26, 2007 6:26 pm

Post by lafflin »

Thanks super.
Post Reply