Jump to content

php forms and checkboxes


poleposters

Recommended Posts

You probably need to clarify your point a little: Wherein lies the problem? Do you need a more general explanation of how checkboxes work and are handled in PHP? Or do you need an idea or two concerning the structure of your db table(s), so the data from the checkboxes can be stored with maximum efficiency?

Something like this

 

<?php

if (isset($_POST['submit'])){

   foreach ($_POST['check'] as $key => $val){

      //this is where you would build your query
      echo $key . ' - ' . $val . '<br>';
      
   }
}

?>

<form>
   <input type="checkbox" name="check[]" value=1 />
   <input type="checkbox" name="check[]" value=2 />
   <input type="checkbox" name="check[]" value=3 />

   <input type="submit" name="submit">
</form>

 

If you give a little more of an explanation it would be easier to show you how to build the query.

Just a little confused about how to handle the checkboxes. I've never used them in a form before.

 

I was thinking about storing the values in individual records along with the user id.

 

how do I check which have been selected then insert them into the database?

 

 

 

 

Checkboxes and php can work in many different ways, so the best way to ask is let us know what you are doing.

 

- You could use checkboxes to perform functions on 1+ objects

- You could use checkboxes to enable/disable options

 

There are more, but hard to think, but any way you want to use them, will have a different explanation.

If you look at the code I supplied above, that will tell you which checkboxes were selected by giving you the value of each one.

 

So try this code and you will see how it works

<?php

if (isset($_POST['submit'])){

   foreach ($_POST['check'] as $key => $val){

      //this is where you would build your query
      echo $val.'<br>';
      
   }
}

?>

<br>
<form method="post">
   1<input type="checkbox" name="check[]" value=1 /><br>
   2<input type="checkbox" name="check[]" value=2 /><br>
   3<input type="checkbox" name="check[]" value=3 /><br>

   <input type="submit" name="submit">
</form>

Basically, just so you don't ask yourself where all the POST data is gone, checkboxes are not sent when unchecked.

So, if you have a checkbox named "blah" and it is not checked, submitting the form will give you an empty $_POST array. Since you might think it would give you an array element named "blah", with false as its value, that might confuse you. It is however quite convenient, as checkboxes (through the html attribute value='....') may also transfer values like "0" or "false" this way.

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.