OK, I am making a Form that will have about 65 check boxes, this data will be pulled from database.
I need to validate form to be sure that 7 (no more no less) are checked.
Can some one post a quick code snippet of the code validation for this?

I have searched and have found some greater than examples but to specific number.

Thanx.

Recommended Answers

I would suggest that you have both client-side and server-side validation. The client-side should prevent users from choosing = 7 options or notify the user that they have chosen = 7 options and refused to submit the form.

A simple version would be:
1) The html should set the …

Jump to Post

Here's the idea, though i have not tested the code, the logic is correct.

<?php

$sql = "SELECT * FROM options LIMIT 65";
$rs = mysql_query($sql);

echo "<form name='frmChk' action='mypage.php' method='post'>";
while($row = mysql_fetch_assoc($rs)){
  $label = $row['option_name'];
  echo "<input type='checkbox' name='chks[]'> $label <br>";
}
echo "<input type='submit' …
Jump to Post

No problem !

Jump to Post

Hi there !
Ok in the file testsel1.php, you need to do the following:
- revalidate the count of checked drivers, and ensure there are 7 (or less ??)
- generate the random id.
- save both drivers and random id

<?php

if(! isset($_POST['submit'])) header("another_page.php");

if(isset($_POST['chks']) && …
Jump to Post

All 15 Replies

Member Avatar

I would suggest that you have both client-side and server-side validation. The client-side should prevent users from choosing = 7 options or notify the user that they have chosen = 7 options and refused to submit the form.

A simple version would be:
1) The html should set the state of each checkbox in the array and the initial count set up as a js variable. If total <> 7 , disable the submit button.
2) A click will ascribe a +1 or -1 to the total (depending if the chkbox has been checked or unchecked). Check total, disable or enable submit button.

The server should valso validate, e.g.

$count = count($_POST['chk_option']);

If this is <> 7, refuse the data and send the user back to the form with an error message. Remember to store the info ($_SESSION/$_COOKIE/querystring and $_GET) from the $_POST variables to replenish the form fields.

Here's the idea, though i have not tested the code, the logic is correct.

<?php

$sql = "SELECT * FROM options LIMIT 65";
$rs = mysql_query($sql);

echo "<form name='frmChk' action='mypage.php' method='post'>";
while($row = mysql_fetch_assoc($rs)){
  $label = $row['option_name'];
  echo "<input type='checkbox' name='chks[]'> $label <br>";
}
echo "<input type='submit' value='Validate & Submit' name='validate' onclick='if(!checkCount()) return false;'></form>";

echo 
"<script language='javascript'>
  function checkCount(){
   var count=0;
   var inputs=document.frmChk.getElementsByTagName('input');
   for(var i=0; i<inputs.length-1; i++){
     if(inputs[i].type == 'checkbox' && inputs[i].checked == true)
        count++;
   }
    if(count != 7){
        alert('You must select exactly 7 checkboxes');
        return false;
     }
     return true; 
 }
</script>";
?>

Thanx very much, I will work with this so far.

I am very much in over my head lol, but I could not find what I was lookin for, so will have to make my own haha.

Think after a few pages I will be ok though.

Thanx again, and I am sure I will be back many times yet.

No problem !

Well 8 days later lol, finally got the first step done.
What I am finding the mosst difficult is integrating into my current site which uses .php & .tpl

Ok, so now my page goes to db, gets the drivers and validates that user has picked 7 exactly,
Now how do I do next step?
I now need to enter the user (also give user a unique ID) and their seven drivers into the db in a table called userdriver10

Here is my page so far

<?php

	$tpl = new template;
	$tpl -> Load("!theme/{$GLOBALS["THEME"]}/templates/fantasy/fselteam.tpl");
	$tpl -> GetObjects();


if (isset($_SESSION["id"])) $tpl->Zone("userStatus", "user");

		else $tpl->Zone("userStatus", "guest");

	if (isset($GLOBALS["LOGIN_FAIL_TYPE"])) {
		if ($GLOBALS["LOGIN_FAIL_TYPE"] == "e.password") $loginError = $GLOBALS["OBJ"]["loginError.password"];
		elseif ($GLOBALS["LOGIN_FAIL_TYPE"] == "e.user") $loginError = $GLOBALS["OBJ"]["loginError.username"];
		elseif ($GLOBALS["LOGIN_FAIL_TYPE"] == "e.bruteforce") $loginError = $GLOBALS["OBJ"]["loginError.bruteforce"];
		elseif ($GLOBALS["LOGIN_FAIL_TYPE"] == "e.active") $loginError = $GLOBALS["OBJ"]["loginError.active"];
	}
	
	$tpl -> AssignArray(array(
		"login.failMessage" => (isset($loginError)?$loginError:NULL)
	));
	// Report all PHP errors (see changelog)
// error_reporting(E_ALL);
include_once('db_conn.php');
$sql = "SELECT * FROM `nascar_standings` ORDER BY driver ASC LIMIT 65";
$rs = mysql_query($sql);
$user = "frank";
$i = 0;
$sel_text = "";
$column = "</tr><tr>";
while($row = mysql_fetch_assoc($rs)){
  $label = $row['driver'];
  $sel_text .= "<td><input type='checkbox' name='chks[]'> $label </td>";
    if (++$i % 4 == 0)
    {
        $sel_text .= $column;
    }
}
$sel_text .= "</tr><tr><td colspan =4 valign = center><input type='submit' value='Validate & Submit' name='validate' onclick='if(!checkCount()) return false;'></td></tr></table></form>";

$sel_text .= "<script type='text/javascript'>
		
	function checkCount(){
		var mincheck = 7;
		var testform = document.getElementById('frmChk');
		var items = testform.getElementsByTagName('input');
		var count = 0;
		
		for (var i=0; i < items.length-1; i++)
		{
			if (items[i].type == 'checkbox' && items[i].checked)
			{
				count++;
			}
		}
		
		if(count != mincheck)
		{
			alert('You must select ' + mincheck + ' Drivers');
			return false;
		}
		return true; 
	}
	
</script>";
$tpl -> AssignArray(array('selteam' => $sel_text));		
$tpl -> Flush();

?>

ooops,
and on the .tpl side I have

<form id='frmChk' action='testsel1.php' method='post' onsubmit='if (!checkCount()) return false;'>

I have action='testsel1.php' there just to test, but I imagine that is where I will need to input back into db?

Anyone?

I think once I get this next step figured out, the rest of the pages I need to make should go alot smoother lol.

Thanx.

Hi there !
Ok in the file testsel1.php, you need to do the following:
- revalidate the count of checked drivers, and ensure there are 7 (or less ??)
- generate the random id.
- save both drivers and random id

<?php

if(! isset($_POST['submit'])) header("another_page.php");

if(isset($_POST['chks']) && count($_POST['chks']) == 7){
   $drivers = $_POST['chks'];

  //generate random id
  $randID = substr(md5(microtime(), -7)) //generates a random string of 7 characters

  //note the sql has an ellipsis(...) where you need to fill in the rest
   $sql = "INSERT INTO user_drivers(user_id, driver1, driver2, ..., driver7) VALUES('$randID', '".$drivers[0]."','".$drivers[1]."','...', '".$drivers[6]."')"

   mysql_query($sql);
   
}
else{
  //output invalid number of drivers specified
}

?>

I am trying to put info into the database, have 3 issues (no errors though)
1, The userid username are empty
2, The drivers name are just "on" (need to assign drivers names to checks? )
3, Page echos query, but DB is still empty.

Result page is

INSERT INTO user_drivers(userid, username, driver1, driver2, driver3, driver4, driver5, driver6, driver7) VALUES('','','on','on',''on', 'on', 'on', 'on', 'on')

DB table structure is

CREATE TABLE `user_drivers` (
  `userid` int(11) NOT NULL,
  `username` varchar(32) character set utf8 collate utf8_unicode_ci NOT NULL,
  `driver1` text character set latin1 NOT NULL,
  `driver2` text character set latin1 NOT NULL,
  `driver3` text character set latin1 NOT NULL,
  `driver4` text character set latin1 NOT NULL,
  `driver5` text character set latin1 NOT NULL,
  `driver6` text character set latin1 NOT NULL,
  `driver7` text character set latin1 NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Form page is

<?php

	$tpl = new template;
	$tpl -> Load("!theme/{$GLOBALS["THEME"]}/templates/fantasy/fselteam.tpl");
	$tpl -> GetObjects();


if (isset($_SESSION["id"])) $tpl->Zone("userStatus", "user");

		else $tpl->Zone("userStatus", "guest");

	if (isset($GLOBALS["LOGIN_FAIL_TYPE"])) {
		if ($GLOBALS["LOGIN_FAIL_TYPE"] == "e.password") $loginError = $GLOBALS["OBJ"]["loginError.password"];
		elseif ($GLOBALS["LOGIN_FAIL_TYPE"] == "e.user") $loginError = $GLOBALS["OBJ"]["loginError.username"];
		elseif ($GLOBALS["LOGIN_FAIL_TYPE"] == "e.bruteforce") $loginError = $GLOBALS["OBJ"]["loginError.bruteforce"];
		elseif ($GLOBALS["LOGIN_FAIL_TYPE"] == "e.active") $loginError = $GLOBALS["OBJ"]["loginError.active"];
	}
	
	$tpl -> AssignArray(array(
		"login.failMessage" => (isset($loginError)?$loginError:NULL)
	));
	// Report all PHP errors (see changelog)
// error_reporting(E_ALL);
include_once('db_conn.php');
$sql = "SELECT * FROM `nascar_standings` ORDER BY driver ASC LIMIT 65";
$rs = mysql_query($sql);
$username = me('username');
$userid = me('id');
$i = 0;
$sel_text = "";
$column = "</tr><tr>";
while($row = mysql_fetch_assoc($rs)){
  $label = $row['driver'];
  $sel_text .= "<td><input type='checkbox' name='chks[]'> $label </td>";
    if (++$i % 4 == 0)
    {
        $sel_text .= $column;
    }
}
$sel_text .= "</tr><tr><td colspan =4 valign = center><input type='submit' value='Validate & Submit' name='validate' onclick='if(!checkCount()) return false;'></td></tr></table></form>";

$sel_text .= "<script type='text/javascript'>
		
	function checkCount(){
		var mincheck = 7;
		var testform = document.getElementById('frmChk');
		var items = testform.getElementsByTagName('input');
		var count = 0;
		
		for (var i=0; i < items.length-1; i++)
		{
			if (items[i].type == 'checkbox' && items[i].checked)
			{
				count++;
			}
		}
		
		if(count != mincheck)
		{
			alert('You must select ' + mincheck + ' Drivers');
			return false;
		}
		return true; 
	}
	
</script>";
$tpl -> AssignArray(array('selteam' => $sel_text));		
$tpl -> Flush();

?>

The insert page is

<?php

if(! isset($_POST['submit'])) header("fhome.php");

if(isset($_POST['chks']) && count($_POST['chks']) == 7){
   $drivers = $_POST['chks'];

include_once('db_conn.php');

  //note the sql has an ellipsis(...) where you need to fill in the rest
   $sql = "INSERT INTO user_drivers(userid, username, driver1, driver2, driver3, driver4, driver5, driver6, driver7) VALUES('".$userid."','".$username."','".$drivers[0]."','".$drivers[1]."',''".$drivers[2]."', '".$drivers[3]."', '".$drivers[4]."', '".$drivers[5]."', '".$drivers[6]."')";

   mysql_query($sql);
   
}
else{
  //output invalid number of drivers specified
}
echo $sql;
?>

I have been able to correct the userid and username, and able to get drivers names in query by adding
value='$label'

Now, for some reason (no error) it seems to work, but just not being inserted into DB?
Thanx again.

here is a sample of my input query echoed

INSERT INTO user_drivers(userid, username, driver1, driver2, driver3, driver4, driver5, driver6, driver7) VALUES('1','planethax','Carl Edwards','Greg Biffle',''Jeff Gordon', 'Jimmie Johnson', 'Juan Pablo Montoya', 'Mark Martin', 'Tony Stewart')

here is a sample of my input query echoed

Ya! I git it, if you look before Jeff Gordon, there was an extra '

Hi Planet,
The reason why the insert could be failing is because the db expects the userid to be an integer, whilst in your case if you are using the following code to generate your userid, then the id wont be an integer but rather a 7 character string. $randID = substr(md5(microtime(), -7)); What you can rather do is, make the userid column, an auto incrementing column, then create another column say - userkey, which stores the 7 character string. Then, modify your insert query to accommodate the new userkey field, and then remove the auto incrementing column(userid):

$userkey = substr(md5(microtime(), -7));
$sql = "INSERT INTO user_drivers(userkey, username, driver1, driver2, driver3, driver4, driver5, driver6, driver7) VALUES('".$userkey."','".$username."','".$drivers[0]."','".$drivers[1]."',''".$drivers[2]."', '".$drivers[3]."', '".$drivers[4]."', '".$drivers[5]."', '".$drivers[6]."')";

Note: the userid has been replaced by userkey in the query. The userid will auto increment itself.

Ahhh, sorry I was not clear, I did get it to work now, it was not inserting before because I had an extra ' in my query (just before Jeff Gordon in my sample)

The reason I am not auto incrementing the userid, is the ID is already set in another spot of my site.

(I have remove the code snippet from earlier to creat a unique ID as I had realized later I could use the one already assigned)

Thanx for all your help, I am starting to get this now.

Cool, that's good news then. :P

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.