Kyle Florence Web Designer

tutorials

PHP and checkboxes

  • Views1530
  • CategoriesPHP
  • Date PublishedNovember 30, 2004

One of the trickier aspects of HTML and PHP integration. In this tutorial, I'm going to focus on one of the ways to get checkboxes to work with PHP.

What's so confusing about all this? Well, say you wanted to code a page that had multiple checkboxes, and you wanted the user to be able to check any number of boxes, click on a button, and have your code deal with each checked box. A good example of this is email scripts (such as horde, or neomail) - you can select the items you want deleted, or moved, and then click the button. Well after the information is submitted, you need to find a way to deal with the results to change the attributes of the emails. I will describe this below.

First we will deal with the HTML. Keep in mind that this is only one of the ways to set this up, you may want it set up differently, but this is what I've found works best with multiple check boxes. In the example I give below, I don't include the while or for loop statement, however, in your actual code you would have one (possibly a mysql loop through results).

<input type="checkbox" name="checked[]" value="<?=$id;?>">

This sets up an array called $checked which will contain various values of the variable $id. Continuing on with the email example, I will show you how to handle the results in a way that is easy to use. Below is the code for this in PHP, In this example I show how you would go about deleting entries from your email page.

for ($i = 0; $i < sizeof($checked); $i++)
{
  if (isset($checked[$i])) {
    $id = $checked[$i];
    $result = mysql_query("DELETE FROM notes WHERE id='$id'") or die(mysql_error());
  }
}

This creates a for loop that loops through all the values of $checked to see whether the checkbox was checked or not. If $checked[$pos] (where $pos is the current value of $i) returns as set, that means the user has checked that box. If it is empty, the user left it unchecked. We can then do what we wish with the result (which is stored in $checked[$pos]) - in this example we called a mysql query to delete all notes that matched the id that was held in $checked[$pos]. I hope this helps you in deciding how you wish to handle checkboxes in PHP.

question? comment? contact me