For the PHP newbie, checkboxes and/or multiple select listboxes can be baffling in the beginning. It’s actually not very hard at all, and is often one of the PHP newbie’s first experience with arrays.

The logic behind checkboxes and multiple select listboxes is identical. Because of this, we’ll get the HTML bit of it done for both:

A. Checkboxes
<input type=”checkbox” name=”foo[]” value=”1″>
<input type=”checkbox” name=”foo[]” value=”2″>
<input type=”checkbox” name=”foo[]” value=”3″>
(etc….)

B. Multiple Select Listboxes
<select name=”foo[]” size=”4″ multiple>
<option value=”apples”>Apples</option>
<option value=”oranges”>Oranges</option>
<option value=”pears”>Pears</option>
<option value=”grapes”>Grapes</option>
<option value=”mangos”>Mangos</option>
</select>

Getting the data out

Now we just have to write the PHP code that will be able to extract the data the user selected from the array we created ($foo[])

// check to be sure at least one option was selected
$foo = $_POST['foo'];
if (count($foo) > 0) {
// loop through the array
for ($i=0;$i<count($foo);$i++) {

// do something - this can be a SQL query,
// echoing data to the browser, or whatever
echo "<li>$foo[$i] \n";

} // end "for" loop

} // endif

Advertisement

Themeforest
ssd-virtual-servers-banner-468x60
Previous post

Burning in effigy... or somethin'

Next post

Creating a Multi-Level Listbox in PHP/mySQL

snipe

snipe

I’m a tech geek/dev/infosec-nerd/scuba diver/blacksmith/sword-fighter/crime fighter/ENTP/warcrafter/activist. I'm the CTO at Mass Mosaic and the CEO of Grokability, Inc. in San Diego, CA. Tweet at me @snipeyhead or read more...

  • dana

    Just wondering if you could give an example of how you would use the selected check boxes in a mysql query using a select statement… such as select * from mytable where check1=’value1′ AND check2=’value2′ AND….; my point is what if one of the check marks is left blank then your query wouldn’t return what you want because it would be searching for a AND check1=’ ‘…

  • You would dynamically construct the query.

    $sql = “select * from table “;

    // there is at least one checkbox selected
    if (count($foo) > 0) {

    $sql .=’ where ‘;

    for ($i=0;$i

  • YuriKolovsky

    What if I want to populate the multiple select listboxes from a MySQL database?

  • elias

    How can validate at least two checkboxes has been ticked by the user? thanks!

  • SorreDerosa

    Hey I am really a newby to PHP and scripting in general for that matter, but how would one possibly add this value to a file? whenever I try I usually get an error saying that “array to string conversion”

    • Hi – can you give me an example of what you’re trying to do?

  • Jake jason

    hello Snipe .. How can i get active and deactive multiple user through Checkbox.. can you give me some suitable example and sugguestion..
    Thanks and Cheers.