Insert multiple check-boxes to db

I’m a little stuck as to why I keep the error: " Error : (1048) Column ‘GC’ cannot be null".

What I’m trying to do is validate and insert data into database, where each check-box has it’s own column in the db.

Previously I had all the the check boxes going into the same column (they were just separated by commas).

Below is the the form:

   <form name="emailform" id="emailform" method="post" action ="<?php echo $_SERVER['PHP_SELF']; ?> ">
			<ul class="e-flyer-check-area">
			           <li> <input type="checkbox" name="GC" value="GC"/> General Contractor</li>
		                   <li> <input type="checkbox" name="HB" value="HB"/> Home Builder </li>
		                   <li> <input type="checkbox" name="RR" value="RR"/> Residental Roofer </li>
		                   <li> <input type="checkbox" name="CR" value="CR"/> Commercial Roofer </li>
		                   <li> <input type="checkbox" name="RS" value="RS"/> Restoration Contractor </li>
		                   <li> <input type="checkbox" name="RN" value="RN"/> Renovator </li>
		                   <li> <input type="checkbox" name="SC" value="SC"/> Stucco Contractor </li>
		                  <li> <input type="checkbox" name="CC" value="CC"/> Ceiling Contractor </li>
			 <ul class="e-flyer-check-area">
		                   <li> <input type="checkbox" name="DC" value="DC"/> Drywall Contractor</li>
		                   <li> <input type="checkbox" name="DB" value="DB"/> Drywall Boarding <span>Contractor</span></li>
		                   <li> <input type="checkbox" name="TC" value="TC"/> Drywall Texture <span>Contractor</span></li>
		                   <li> <input type="checkbox" name="DF" value="DF"/> Drywall Finishing <span>Contractor</span></li>
		                   <li> <input type="checkbox" name="FC" value="FC"/> Framing Contractor </li>
		                   <li> <input type="checkbox" name="IN" value="IN"/> Insulator </li>
		                   <li> <input type="checkbox" name="SC" value="SC"/> Masonry Contractor </li>
		                   <li> <input type="checkbox" name="WP" value="WP"/> Water Proofer </li>

		           <ul class="e-flyer-submit-area">
	                            <li class="divider2"></li>
	                            <li> <input type="text" name="name" id="name" placeholder="Name*" value="<?php echo $_POST['name']; ?>" /> </li>
	                            <li> <input type="text" name="email" id="email" placeholder="E-mail*" value="<?php echo $_POST['email']; ?>" /></li>
	                            <li> <input type="checkbox" name="opt" value="<?php echo 'opt-in';?>" > Yes, I agree to opt In!* </li>
	                            <li> <input type="submit" name="submit" class="submit btn btn-lt-grey" value="Submit"/> </li>

The PHP:

	                    $name 	= 	$_POST['name'];
	                    $email 	= 	$_POST['email'];
	                    $opt 	=	$_POST['opt'];
	                    $GC 	= 	$_POST['GC'];
	                    //$HB		=	$_POST['HB'];
	                <div id="e-flyer-validate">
		                            $booValidateOK = 1;
		                            $strValidationMessage = "";

		                            if(strlen($name) < 3){
		                                // $boolValidateOK = 0;
		                                // $strValidationMessage .= "\n <li>Please fill in a name.</li>"; 

		                            //validate e-mail
		                            $emailValidate = validate_email($email);
		                                $boolValidateOK = 0;
		                                $strValidationMessage .= "\n <li>please fill in a proper e-mail.</li>";  

		                            //validate opt-in
		                                $boolValidateOK = 0;
		                                $strValidationMessage .= "\n <li>Please check opt in.</li>"; 
		                            //validate checkboxes
		                            //names of posted checkboxes
		                            /*if(!empty($_POST['info'])) {
		                            // Counting number of checked checkboxes.
		                            	$checked_count = count($_POST['info']);
		                            	echo "You have selected following ".$checked_count." option(s): <br/>";
		                            	// Loop to store and display values of individual checked checkbox.
		                            	foreach($_POST['info'] as $selected) {
		                            		echo "<p>".$selected ."</p>";
		                            	echo"Please Select at least one Category";
		                            }	*/

		                        }//end of submit

		                        if($booValidateOK == 1){

		                           	//$info = ($_POST['info[]']);
									//$pieces = implode(", ",$info);
		                            if(($email !="" && $opt != "")){

		                            	//mysqli query
		                            	$results = "INSERT INTO Emails (name, email, opt, GC) VALUES (?, ?, ?, ?)";
		                            	$statement = $conn->prepare($results);

		                            	//bind parameters for markers, where (s = string, i = integer, d = double, b = blob) 
		                            	$statement->bind_param('ssss', $name, $email, $opt, $GC);

		                            	if($statement->execute()) {
		                            		//print 'Success';
		                            		die('Error : ('. $conn->errno .') '. $conn->error);
		                            }//end of insert
		                        }//close here

		                        function validate_email( $email ){
		                            $email = trim( $email ); # removes whitespace
		                            if(!empty($email) ):
		                                //  validate email address syntax
		                                if( preg_match('/^[a-z0-9\_\.]+@[a-z0-9\-]+\.[a-z]+\.?[a-z]{1,4}$/i', $email, $match) ):
		                                return strtolower($match[0]); # valid!
		                            return false; # NOT valid!
		                        }// close validate_email function  

		                        echo $strValidationMessage;

If someone could point me in the right direction, that would be great!

It would be in this line (hint: what’s its name?)

When a form is sent to PHP via post, for any check-boxes that aren’t “checked” or any radio buttons that haven’t had an option selected, there will be nothing sent. You need to use isset() on each checkbox field.

is there away I could do this as an array, so I can validate the check-boxes as whole?

for example:

<input type="checckbox" name ="info[GC]" value="GC" ..... />
<input type="checckbox" name ="info[HB]" value="HB" ..... />

Just do “info” in the name, and the values will reflect in the POST array. No need to add the value to the name attribute as you have done.

That’s not necessarily the issue I’m having, it’s getting the the values of the check - boxes to separate into to separate columns in the db.

For example the first checkbox is : General Contractor so the input would be:

<p><input type="checkbox"  name="info[]" value ="<?php echo 'GC';?>"/>General Contractor</p>
<p><input type="checkbox"  name="info[]" value ="<?php echo 'HB';?>"/>Home Builder</p>


in my db I currently have columns for the following: name, email, opt-in, timedate, GC, HB, and info (was currently used to hold all the values of the checkbox)…

So you’ve got fields in the database for every one of the checkboxes. (We can debate the efficacy of this database design later.)

To address the immediate problem: If a checkbox is not checked, it’s value (and thus, the name) is NOT sent by the browser.

So when you go to process the data, there is no $_POST[‘GC’] (or whatever you’re looking for); the field is not set. It’s not 0, not null, not “unchecked”… the key simply doesnt exist in the array.

What you would need to do is to check to see if the field exists in the post data, and act accordingly:
if(isset($_POST[‘GC’])) { $gc = 1; } else { $gc = 0; }

and then insert the value of $gc to that field.
(or true/false, or whatever your database field is expecting for a value.)

[PS: this can be shorthanded as $gc = (isset($_POST[‘GC’])) ? 1 : 0; ]

To address “can it be done with arrays”… the answer is yes, but now we’re going to be using some array functions. Let’s take RyanReese’s example.

<input type='checkbox' name='info[]' value='gc'>

<input type='checkbox' name='info[]' value='hr'>

<input type='checkbox' name='info[]' value='tr'>

<input type='checkbox' name='info[]' value='bl'>

So, with those checkboxes, and knowing that the browser wont send any data that isnt checked, we can manipulate and compare arrays.

$roles = array("gc","hr","tr","bl"); //Array must contain all possible entries.
$setAsTrue = array_intersect($_POST['info'],$roles);
$setAsFalse = array_diff($roles,$_POST['info']); //Note that the arrangement of these arguments is important due to how the array functions work!.

Now foreach $setAsTrue and $setAsFalse, compiling your database entry.

[PS: Note that I intersect the true values, instead of just taking the values of $_POST[‘info’]. This sanitizes your data to make sure nothing oddball gets injected.]

Thanks for the reply, a friend and I solved this!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.