Jump to content

How to save checkbox values/selections to mysql database


learningPHP1

Recommended Posts

Hello everybody,

 

I'm having probelms saving the valuses or the selections made from a checkbox.

 

For most part the code works but the selection/data is saved only if all 3 options are checked in the checkbox. But with the checkbox the user has the option to either to sellect all or some of the options so how do i account for this in the mysql statement?


<?php

if(isset($_POST['button']))
{     $devices_returned = $_POST['office']; 

      $values = array();
   
foreach($devices_returned as $selection )
{	if($selection)
	{ $values[ $selection ] = 1;  }
    	 else 
	{ $values[ $selection ] = 0;  } 
  } 	

$insert1 = "INSERT INTO test_location (`desk`, `computer`, `whiteboard`) 
          VALUES ({$values['desk']}, {$values['computer']}, {$values['whiteboard']})"; 

?>

html code
<form name="checkbox" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST"> 
    <input type="checkbox" name="office[]" value="desk"> Desk 
    <input type="checkbox" name="office[]" value="computer"> Computer 
    <input type="checkbox" name="office[]" value="whiteboard"> whiteboard 
    <br> 
    <input type="submit" value="Submit" name="button"> 
</form>

if(isset($_POST['button'])){     
$devices_returned = $_POST['office']; 
$office = array('desk','computer','whiteboard');
$values = array();	

foreach($office as $selection){	
	if(in_array($selection,$devices_returned)){ 
		$values[ $selection ] = 1;  
	}else{ 
		$values[ $selection ] = 0;  
	} 
}
}

Probably it's better to check if a checkbox was checked as your primary condition.

<?php
if(isset($_POST['office'])){     
$devices_returned = $_POST['office']; 
$office = array('desk','computer','whiteboard');
$values = array();	

foreach($office as $selection){	
	if(in_array($selection,$devices_returned)){ 
		$values[ $selection ] = 1;  
	}else{ 
		$values[ $selection ] = 0;  
	} 
}
$insert1 = "INSERT INTO test_location (`desk`, `computer`, `whiteboard`) 
   VALUES ({$values['desk']}, {$values['computer']}, {$values['whiteboard']})";
mysql_query($insert1) or die(mysql_error());    
}
?>

<form name="checkbox" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST"> 
    <input type="checkbox" name="office[]" value="desk"> Desk 
    <input type="checkbox" name="office[]" value="computer"> Computer 
    <input type="checkbox" name="office[]" value="whiteboard"> whiteboard 
    <br> 
    <input type="submit" value="Submit" name="button"> 
</form>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.