Jump to content

Recommended Posts

I am making a registration form where users indicate a level of interest in text boxes. The catch is that they cannot use the same level of interest in any two of the boxes. I thought I had a good script to validate them, but it won't work properly. No errors, it just tells me that there are duplicates even when there aren't. Here is the code. Any help is appreciated.

 

<?php 
require_once('connections/connDB.php'); 
session_start();
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "register")) {
$_SESSION['user'] = $_POST['email'];

// Initialize array for error messages
$error = array();
// Remove whitespace and check for values
$_POST['email'] = trim($_POST['email']);
$_POST['firstname'] = trim($_POST['firstname']);
$_POST['lastname'] = trim($_POST['lastname']);
$_POST['phone'] = trim($_POST['phone']);
$_POST['state'] = trim($_POST['state']);

// check to see if the user supplied an email address and if the email address is in the correct format
if (empty($_POST['email'])) {
	$error['email'] = 'Please enter your email address.';
	} 
elseif (!preg_match('/^[^@]+@[^\s\r\n\'";,@%]+$/', $_POST['email'])) {
	$error['emailinvalid'] = 'Your email address is invalid.';
	}

// check to see if the user supplied a first name
if (empty($_POST['firstname'])) {
	$error['firstname'] = 'Please enter your first name.';
	}

// check to see if the user supplied a last name
if (empty($_POST['lastname'])) {
	$error['lastname'] = 'Please enter your last name.';
	}

// check to see if the user supplied a phone number and if the phone number is in the correct format
if (empty($_POST['phone'])) {
	$error['phone'] = 'Please enter your phone number.';
	} 
elseif (!preg_match("/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/s", $_POST['phone'])) { 
	$error['phoneinvalid'] = 'Please enter your phone number in the correct format.';  
	}

// check to see if the user supplied a state
if (empty($_POST['state'])) {
	$error['state'] = 'Please choose a state.';
	}

// check for duplicate rating values	
$cevss = $_POST['cevssrank'];
$occs = $_POST['occsrank'];
$trtw = $_POST['trtwrank'];
$ppcmr = $_POST['ppcmrrank'];

if ($cevss == $occs || $cevss == $trtw || $cevss == $ppcmr || $occs == $trtw || $occs == $ppcmr || $trtw == $ppcmr) {
	$error['duplicate'] = 'Cannot have duplicate rating values.';
	}

// if no errors, insert the details into the database
if (!$error) {

  		$insertSQL = sprintf("INSERT INTO fipse4readers 
	(email, firstname, lastname, phone, `state`, cevss, occs, trtw, ppcmr, cevssrank, occsrank, trtwrank, ppcmrrank, registered) 
	VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['email'], "text"),
                       GetSQLValueString($_POST['firstname'], "text"),
                       GetSQLValueString($_POST['lastname'], "text"),
                       GetSQLValueString($_POST['phone'], "text"),
                       GetSQLValueString($_POST['state'], "text"),
                       GetSQLValueString(isset($_POST['cevss']) ? "true" : "", "defined","'Y'","'N'"),
                       GetSQLValueString(isset($_POST['occs']) ? "true" : "", "defined","'Y'","'N'"),
                       GetSQLValueString(isset($_POST['trtw']) ? "true" : "", "defined","'Y'","'N'"),
                       GetSQLValueString(isset($_POST['ppcmr']) ? "true" : "", "defined","'Y'","'N'"),
                       GetSQLValueString($_POST['cevssrank'], "int"),
                       GetSQLValueString($_POST['occsrank'], "int"),
                       GetSQLValueString($_POST['trtwrank'], "int"),
                       GetSQLValueString($_POST['ppcmrrank'], "int"),
                       GetSQLValueString($_POST['registered'], "date"));

  	mysql_select_db($database_connDB, $connDB);
  	$Result1 = mysql_query($insertSQL, $connDB);

if (!$Result1 && mysql_errno() == 1062) {
    	$error['user'] = $_POST['email'] . ' is already in use.';
  		} elseif (mysql_error()) {
    		$error['dberror'] = 'Sorry, there was a problem with the database. Please try later.';
  			} else {
  				$insertGoTo = "registered.php";
  				if (isset($_SERVER['QUERY_STRING'])) {
    				$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    				$insertGoTo .= $_SERVER['QUERY_STRING'];
  					}
  				header(sprintf("Location: %s", $insertGoTo));
			}
	}
}
mysql_select_db($database_connDB, $connDB);
$query_rsGetState = "SELECT abbreviation FROM `state` ORDER BY abbreviation ASC";
$rsGetState = mysql_query($query_rsGetState, $connDB) or die(mysql_error());
$row_rsGetState = mysql_fetch_assoc($rsGetState);
$totalRows_rsGetState = mysql_num_rows($rsGetState);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>FIPSE 4</title>
<link rel=stylesheet type="text/css" href="style.css">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body bottommargin="0" leftmargin="0" rightmargin="0" topmargin="0" background="images/background.jpg">
<?php include ('header.php'); ?>
<?php include ('topbar.php'); ?>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top">
<?php include ('menu.php'); ?>
<td width="100%">
<table width="90%" border="0" align="center" cellpadding="10" cellspacing="0">
    <tr valign="top">
	<td> 
        <br />
        Welcome to the reader registration website for the FIPSE 4 competitions<br />
        <br />
        Please complete the registration form below to be considered as a reader.<br>
        <br />
        <table width="70%" border="0" align="center" cellpadding="5" cellspacing="0">
        	<tr>
            	<td>
                <form action="<?php echo $editFormAction; ?>" method="POST" name="register" id="register">
                <?php
                if (isset($error)) {
		    	echo '<div align="center"><span style="color: red">';
		        	foreach ($error as $alert) {
		      	echo "$alert<br />\n";
		      	}
		  	echo '</div></span>';
			// remove escape characters from POST array
               	if (PHP_VERSION < 6 && get_magic_quotes_gpc()) {
               		function stripslashes_deep($value) {
                    	$value = is_array($value) ? array_map('stripslashes_deep',
                        	$value) : stripslashes($value);
                      	return $value;
                    	}
                    $_POST = array_map('stripslashes_deep', $_POST);
                  	}
		    }
		  	?>
                <table width="90%" border="0" align="center" cellpadding="5" cellspacing="0">
                <tr>
                	<td><div align="right">Email Address:</div></td>
                    <td><input value="<?php if (isset($_POST['email'])) {
echo htmlentities($_POST['email'], 
ENT_COMPAT, 'UTF-8');} ?>" name="email" type="text" id="email" size="35">
                      <span class="style6">*</span></td>
               	</tr>
               	<tr>
               		<td><div align="right">First Name:
             		    </div>
               		</label></td>
                    <td><input value="<?php if (isset($_POST['firstname'])) {
echo htmlentities($_POST['firstname'], 
ENT_COMPAT, 'UTF-8');} ?>" name="firstname" type="text" id="firstname" size="20">
                      <span class="style6">*</span></td>
              	</tr>
              	<tr>
                 	<td><div align="right">Last Name:</div></td>
                    <td><input value="<?php if (isset($_POST['lastname'])) {
echo htmlentities($_POST['lastname'], 
ENT_COMPAT, 'UTF-8');} ?>" name="lastname" type="text" id="lastname" size="20">
                      <span class="style6">*</span></td>
              	</tr>
              	<tr>
               		<td><div align="right">Phone Number:
             		    </div>
               		</label></td>
              		<td><input value="<?php if (isset($_POST['phone'])) {
echo htmlentities($_POST['phone'], 
ENT_COMPAT, 'UTF-8');} ?>" name="phone" type="text" id="phone" size="20">
              		  <span class="style6">* (Use 000-000-0000 Format)</span></td>
             	</tr>
              	<tr>
               		<td><div align="right">State:</div>
               		  </td>
                    <td>
                    <select name="state" id="state">
				<?php
				do {  
				?>
				<option value="<?php echo $row_rsGetState['abbreviation'];
					if (isset($_POST['state']) && $_POST['state'] == $row_rsGetState['abbreviation']) {
						echo 'selected="selected"';} ?>">
						<?php echo $row_rsGetState['abbreviation']?></option>
				<?php
					} while ($row_rsGetState = mysql_fetch_assoc($rsGetState));
  							$rows = mysql_num_rows($rsGetState);
  							if($rows > 0) {
    							mysql_data_seek($rsGetState, 0);
  							$row_rsGetState = mysql_fetch_assoc($rsGetState);
  								}
				?>
                    </select>
                      <span class="style6">*</span></td>
              	</tr>
        	</table>

                    <br>
                    <div align="center" class="style6">* Indicates a required field</div>
                    <br>
                    Listed below are the programs you can register to become a reader for. <br>
                    <br>
                    <strong>Step 1)</strong> Please put a check in the checkbox next to the program you wish to read for. There is no limit to how many programs you may choose. <br>
                    <br>
                    <strong>Step 2)</strong> After you have decided which program(s) you want to read for, please rank each program according to level of interest. You may not give two programs the same rank. Please use only values "1" through "4", with "1" being the most interested and "4" being the least. (Example: Put a "1" next to the program you are most interested in reading, a "2" next to the program you are 2nd most interested in readting, etc.)<br>
                    <br>
                    <table width="100%" border="0" align="center" cellpadding="5" cellspacing="0">
                      <tr>
                        <td width="6%" bgcolor="#999999"><div align="center"><strong>Interested</strong></div></td>
                        <td width="85%" bgcolor="#999999"><div align="center"><strong>Program Name</strong></div></td>
                        <td width="9%" bgcolor="#999999"><div align="center"><strong>Rank</strong></div></td>
                      </tr>
                      <tr>
                        <td><div align="center">
                          <input name="cevss" type="checkbox" id="cevss" value="Y"
                          <?php if(isset($_POST['cevss'])) {
					  	echo '"checked=checked"';
						} ?>
                          >
                        </div></td>
                        <td>84.116G – Centers of  Excellence for Veteran Student Success (CEVSS)</td>
                        <td><div align="center">
                          <input value="<?php if (isset($_POST['cevssrank'])) {
echo htmlentities($_POST['cevssrank'], 
ENT_COMPAT, 'UTF-8');} ?>" name="cevssrank" type="text" id="cevssrank" size="5" maxlength="1">
                        </div></td>
                      </tr>
                      <tr>
                        <td><div align="center">
                          <input name="occs" type="checkbox" id="occs" value="Y"
                          <?php if(isset($_POST['occs'])) {
					  	echo '"checked=checked"';
						} ?>
                          >
                        </div></td>
                        <td>84.116H – Off-Campus  Community Service (OCCS)</td>
                        <td><div align="center">
                          <input value="<?php if (isset($_POST['occsrank'])) {
echo htmlentities($_POST['occsrank'], 
ENT_COMPAT, 'UTF-8');} ?>" name="occsrank" type="text" id="occsrank" size="5" maxlength="1">
                        </div></td>
                      </tr>
                      <tr>
                        <td><div align="center">
                          <input name="trtw" type="checkbox" id="trtw" value="Y"
                          <?php if(isset($_POST['trtw'])) {
					  	echo '"checked=checked"';
						} ?>
                          >
                        </div></td>
                        <td>84.116K – Training  for Realtime Writers  (TRTW)</td>
                        <td><div align="center">
                          <input value="<?php if (isset($_POST['trtwrank'])) {
echo htmlentities($_POST['trtwrank'], 
ENT_COMPAT, 'UTF-8');} ?>" name="trtwrank" type="text" id="trtwrank" size="5" maxlength="1">
                        </div></td>
                      </tr>
                      <tr>
                        <td><div align="center">
                          <input name="ppcmr" type="checkbox" id="ppcmr" value="Y"
                          <?php if(isset($_POST['ppcmr'])) {
					  	echo '"checked=checked"';
						} ?>
                          >
                        </div></td>
                        <td>84.116T – Pilot  Program for Course Material Rental (PPCMR)</td>
                        <td><div align="center">
                          <input value="<?php if (isset($_POST['ppcmrrank'])) {
echo htmlentities($_POST['ppcmrrank'], 
ENT_COMPAT, 'UTF-8');} ?>" name="ppcmrrank" type="text" id="ppcmrrank" size="5" maxlength="1">
                        </div></td>
                      </tr>
                    </table>
                    <br>
                    <div align="center">
                      Thank you for your help! When you are finished press the submit button.</div>
                      <br>
                      <div align="center">
                      <input type="submit" name="submit" id="submit" value="Submit">
                      </div>
                      <input name="registered" type="hidden" id="registered" value="<?php echo date('Y-m-d H:i:s'); ?>">
                      <input type="hidden" name="MM_insert" value="register">
                </form>              </td>
            </tr>
          </table></td>
    </tr>
</table>
</td>
</tr>
</table>
</body>
</html>
<?php
mysql_free_result($rsGetState);
?>

Link to comment
https://forums.phpfreaks.com/topic/208956-what-should-be-a-simple-form-validation/
Share on other sites

I have found that when working with compound conditions in an if statement it is always safer to add parenthesis around each individual condition. It does not cost much (parenthesis are really cheap these days) and it never hurts (unless you put them in the wrong place).

 

if ( ($cevss == $occs) || ($cevss == $trtw) || ($cevss == $ppcmr) 
||   ($occs == $trtw) || ($occs == $ppcmr) || ($trtw == $ppcmr) ) {

 

Personally, I always use 'and' and 'or' instead of '&&' and '||'. That's just a personal thing though. The order of precedence is different between them, so you don't want to mix them in the same statement unless you know exactly what is happening.

 

You are not checking to see if a box is checked.  If any boxes are left unchecked, you will still get the ranking text box. Which will probably be empty. So you have duplicate values (empty).  You might try something like this:

 

// check for duplicate rating values   
$ranks = array();
if (isset($_POST['cvess'])) { // Is the cvess box checked?
  $ranks['cevss'] = $_POST['cevssrank'];
}
if ( (isset($_POST['occs'])) { // Is the occs box checked?
  $ranks['occs'] = $_POST['occsrank'];
}
if ( (isset($_POST['trtw'])) { // Is the trtwbox checked?
  $ranks['trtw'] = $_POST['trtwrank'];
}

if ( (isset($_POST['ppcmr'])) { // Is the ppcmrbox checked?
  $ranks['ppcmr'] = $_POST['ppcmrrank'];
}

$uniq = array_unique($ranks);
if ( count($uniq) != count($ranks)) {
    // There are duplicate rankings ...
}

This may not be the "best" way to do it.  But it should work.  The $uniq array will only have unique entries from the $ranks array. So if all of the ranks are unique, then both arrays should have the same number of elements.

 

You could simplify this by changing the input fields to something like this:

<input value="" name="rank[cevss]" type="text" id="cevssrank" size="5" maxlength="1">

 

Then they will show up as $_POST['rank']['cevss'] (I'm not sure if you need quotes in the INPUT tag or not, try it out:

<input value="" name="rank['cevss']" type="text" id="cevssrank" size="5" maxlength="1">

 

OK, that fixed the problem of giving me the duplicate error even when there weren't any duplicates, but now it won't detect the duplicate values. I tried making the last if statement ==, but then it always gives me the duplicate error. Any ideas?

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.