Jump to content

How do I insert multiple checkbox data as 1 or 0 in multiple columns?


ke-jo

Recommended Posts

Hello all,

   I am trying to learn OOP in PHP so please forgive my ignorance. I seem to be having difficulty inserting data into my database from checkbox items. My database has a column for each each fruit. I would like for each column to be populated with either a one(1) for checked or a zero(0)  for not checked. Currently, my attempts have failed. I can either get all checkboxes to insert all zeros or I can get the first column to insert a one(1) while the others as zeros. Is there anybody here that can help me figure out what I am doing wrong and help me to re-work my code so I can get this to work? If anybody can help me using OOP methods that would be fantastic. Thank you all in advance.

 

$preffruit->create_preffruit(array(

  'fruit_apple' => escape(Input::get(['fruit_selection'][0]) ? 1 : 0),
  'fruit_orange' => escape(Input::get(['fruit_selection'][1]) ? 1 : 0),
  'fruit_banana' => escape(Input::get(['fruit_selection'][2]) ? 1 : 0),
  'fruit_pear' => escape(Input::get(['fruit_selection'][3]) ? 1 : 0),
  'fruit_kiwi' => escape(Input::get(['fruit_selection'][4]) ? 1 : 0)

  ));

<input type="checkbox" name="fruit_selection[]" value="fruit_apple">
<input type="checkbox" name="fruit_selection[]" value="fruit_orange">
<input type="checkbox" name="fruit_selection[]" value="fruit_banana">
<input type="checkbox" name="fruit_selection[]" value="fruit_pear">
<input type="checkbox" name="fruit_selection[]" value="fruit_kiwi">



public function insert_preffruit($table, $fields = array()) {
			
			$keys = array_keys($fields);
			$values = '';
			$x = 1;			
			
			foreach($fields as $field) {
				$values .= '?';
				if($x < count($fields)) {
					$values .= ', ';
				}
				$x++;
			}		
				
				$sql = "INSERT INTO preffruit (`user_id`, `" . implode('`, `', $keys) . "`) VALUES (LAST_INSERT_ID(), {$values})";		
			
			if(!$this->query($sql, $fields)->error()) {
				return true;
			}			
			
			return false;
		}

 

Edited by ke-jo
Link to comment
Share on other sites

A checkbox is only submitted when it is checked. You cannot simply look at [0] and [1] and so on to know what value it has.

The answer is, hopefully not too surprisingly, to look at the value. You've got it right there. fruit_selection will be an array and all you have to do is see if that array contains each fruit.

  • Great Answer 1
Link to comment
Share on other sites

You are using the "keys" from the user submitted data as the field names in your query! DO NOT DO THIS! Never trust the data from the user. Just because you provided the field names in the form does not mean that the user will submit that back. The user could arbitrarily send any field names or even malicious SQL code to expose or corrupt your DB.

 

 

  • Great Answer 1
Link to comment
Share on other sites

@Psycho Thanks for your feedback. I have removed the PDO on " $sql = "INSERT INTO preffruit (`user_id`, `" . implode('`, `', $keys) . "`) VALUES (LAST_INSERT_ID(), {$values})"; " Because my code is failing. I need to keep it simple so I can try to figure out how to get it to work. I am trying to crawl before I walk. You are way ahead of my abilities right now. I promise you I will replace the PDO when my code works. Thanks.

Link to comment
Share on other sites

@requinix Thanks for the reply. I am still having issues with this code. I removed the array brackets from the name, ( name="fruit_selection" ) . Without the array I am now able to get the entries into the database properly as "1" for selected and "0" for un-selected. However, since there is no array that is holding these input names my validation class method does not work. My validation is suppose to show an error if none of these checkboxes are selected. I had to change each input name to its own identity ( fruit_selection_apple ), then set my validation like this:

 

       public function check($source, $items = array()) {
			foreach($items as $item => $rules) {
				foreach($rules as $rule => $rule_value) {
										
					$value = trim($source[$item]);					
					$item = escape($item);

               $checkboxvalue =                 
                        (isset($_POST['fruit_selection_apple'])) ||
                        (isset($_POST['fruit_selection_orange'])) ||
                        (isset($_POST['fruit_selection_banana'])) ||
                        (isset($_POST['fruit_selection_pear'])) ||                        
                        (isset($_POST['fruit_selection_kiwi'])
                    )                              
                    if($rule === 'atleastone' && empty($checkboxvalue)) {
                        $this->addError("{$item} You must select at least one checkbox.");
                    }

However, this is NOT OOP PHP. I had to hard code these values into the validation class. I am also now getting a notice, "Notice: Undefined index: fruit_selection " on:

         $validate = new Validate();			
			$validation = $validate->check($_POST, array(
				'fruit_selection' => array(
					'atleastone' => true					
				),

Can anybody help me to re-code this to work without the notice and to keep it as OOP? I know this is a bit complex but I would appreciate the help.

 

             Thanks

Edited by ke-jo
Link to comment
Share on other sites

@requinix Then how would you suggest I get the values to be entered into the individual database columns? As stated earlier the array did not place the entries into the individual columns. Can you actually show me some working code? Thanks

Example:

column apple = 0,

column orange = 1,  

column banana = 1,

column pear = 0,

column kiwi = 1.

Link to comment
Share on other sites

I don't know what your checkboxes look like now, but you've put the name of the fruit as an array key or as an array value.

If you put it as a key then test if each fruit was selected using isset(). If you put it as a value then test using in_array().

Link to comment
Share on other sites

Quote

Obviously the administrator does not know PHP enough to help someone at this skill level.

Allow me to summarize the posts in this thread:

  1. (OP) I'm trying to learn OOP. Regardless, I have some problems with checkboxes in that I can't tell which checkboxes are which.
  2. (me) Checkboxes are only submitted when they're checked. If you need to know which fruits were selected then it requires looking at the values in the checkbox array.
  3. (Psycho) Don't use submitted data as field names in a query. The user could have done something malicious that will mess up your application.
  4. (OP to Psycho) I removed some code but I still don't know what's wrong.
  5. (OP to me) I completely changed the checkboxes and the code so it doesn't use an array. Here is some validation code that no longer works because it expected an array.
  6. (me) Why did you completely change how the checkboxes and the code look? The array from before was fine.
  7. (OP) So what do I do? It still doesn't work. Please give me code. Here's another explanation of what I want.
  8. (me) I don't know what "completely changed" is but you need the fruit name in the array somehow. You can then check if each fruit was selected using one of two methods.
  9. (OP) This isn't helpful. I'm going to take my question somewhere else.
  10. (me) I don't think that will make a difference.

We weren't going to give you the new code. Not even sure we had enough information to do so. But we can try to tell you what is wrong and how it needs to be changed.

Unfortunately, that wasn't good enough.

Link to comment
Share on other sites

Guest
This topic is now 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.