Using Checkboxes for User Interaction


#1

Using Checkboxes for User Interaction

Overview

The checkbox plays an important role in user interaction in many web applications (I apologize in advance for stupefying you with the term ‘web application’; It’s just that calling it a ‘script’ or ‘PHP page’ is too limiting and as a beginner it is helpful to start thinking of even the smallest scripts as applications. You’ll thank me later.). A common use for checkbox inputs is to allow the user to select a number of items and carry out an operation on just those selected items. For example, deleting unwanted messages from a web based mailbox. They also can allow the user a way to configure application features or administrate content.

When used as part of a application interface, the user is typically presented with a list of items they can select by marking a checkbox beside each item. The list is contained within a HTML form so when user then submits the the form the items selected can be communicated to the application. Additional input may indicate what action the user wishes to take.

This approach is often better than a displaying links beside each item, one for each type of process. The checkbox approach is scalable in that any one of a number of actions can be applied to the selected items. It gives the user choice over what is done with the items. It also follows the familiar user interface process of selecting an ‘object’ before acting on it (the noun-verb metaphor).

Single Unrelated Checkbox Inputs

You are a probably familiar with seeing a checkbox input on a form. You should be familiar with web forms before attempting to use checkbox inputs in your applications.

<input type="checkbox" name="sideorder" value="Breadsticks" />Do you want breadsticks with your pizza?

The checkbox allows the user to select an item and communicate that selection to your application. When submitted as part of a form, if the checkbox input has been checked by the user the value will be available for use. If it has not been checked, the input name and value are not sent by the browser in the form submission. Neither will be available in your program. This means you can test for the existence of a checkbox name to see if it has been checked.

[php]
print ‘

Side of

’;
print ‘
    ’;
    if($_POST[‘sideorder’])
    {
    print ‘
  • Breadsticks
  • ’;
    }
    print ‘
’;
[/php]

Multiple Related Checkbox Inputs

A number of checkbox inputs may be grouped by name. These related checkbox inputs allows the user to select more than one item and communicate that selection of items to your application.

To return multiple values for a series of related checkbox inputs, PHP returns an array containing the values of any checked inputs. Checkbox inputs that are not checked do not appear in the array. The special status of related or multiple checkbox inputs is indicated by adding brackets to the input name (This may change from name to id attribute in the future).

Code for a series of checkboxes will appear very similar to this:

<input type="checkbox" name="topping[]" value="Extra Cheese" />
<input type="checkbox" name="topping[]" value="Green Pepper" />
<input type="checkbox" name="topping[]" value="Onion" />
<input type="checkbox" name="topping[]" value="Pepperoni" />
<input type="checkbox" name="topping[]" value="Italian Sausage" />
<input type="checkbox" name="topping[]" value="Anchovies" />

This property makes checkboxes useful for more than just selecting among items on a data entry form, but is an important tool in building administrative or user interfaces that control content or act on the user’s wishes. For example, it might allow the user to select multiple files for a web based file explorer or select a number of email items for deleting in a webmail application.

Using the Checkbox to Drive User Interaction

A checkbox interface is especially helpful for managing content that is displayed through tabular listings, which is the format most applications return query results in.

Let’s review the process with a simple example that does not require any external input from a database. The checkbox items will be a static HTML form. The following code accepts the input from the Toppings form, printing those items that are checked.

Example 1

[php]

<?php if(isset($topping)) { print '

Toppings:

'; // process items $n = count($topping); for($i = 0; $i <= $n; $i++) { print $topping[$i] . "
"; } } else { ?> Extra Cheese
Green Pepper
Onion
Pepperoni
Italian Sausage
Anchovies
<?php } ?>

[/php]

If the form has been submitted (this condition is detected by the checkbox having a value), the checked items are printed out.

This has been a very safe example. The only action was to print items. I wanted you to see this example before moving on to more serious applications the same principle. If we were deleting items in a database we could do some serious damage. Always backup any database you are working on, try to work on a development database before moving code to a production database and back that one up too before making any code changes.

Now, we will try the same thing in a database version. We will list items from a database and print those the use checks. We will also get a little fancy with our coding so that we do not have to write all those checkboxes out manually.

We will use the popular MySQL database in this example.

To help you understand the code, you need to know something about the database table we are listing items from. Imagine a database of films. Each film can have annotations associated with it. We want a listing of the notes for a particular film. Each note has a unique identifier (also serving as primary key), the id of the film the notes are for and a shortened version of the item title. The first 32 characters of the note are used as a sort of title or abstract to identify the note as an aid to memory.

A function is used to generate each checkbox input. The make_item_control($title,$value) generates a table row with a checkbox input for inclusion in the form table. You could of course separate this out from the HTML table more, but for our example this is good enough.

Example 2

[php]

<?php // example code for checkbox.txt // confirmed working: Friday, March 07, 2003 // Configuration information for connecting to database // Contains $db_name, $db_user, $db_pass, $db_host // for connection. // Enter your database host name here. $db_host = "YourDatabaseHost"; // Enter your database password here. $db_pass = "YourDatabasePassword"; // Enter your database user name here. $db_user = "YourDatabaseUsername"; // Enter the name of your database here. $db_name = "YourDatabaseName"; // Connect to database $db_conn = @mysql_pconnect($db_host, $db_user, $db_pass); // Check for database unavailable if (!$db_conn) { print "ERROR - failed to create connection: " . mysql_error(); } function make_item_control($value,$title) { $content = ' '.$title.''; return $content; } if($p_print_checked) { // process items $n = count($item); for($i = 0; $i <= $n; $i++) { print urldecode($item[$i]) . "
"; } } else { // list items // database query here $sql = "SELECT note_id,film_id,LEFT(text,32) AS item_name FROM note ORDER BY film_id ASC;"; $result = mysql_db_query($db_name,$sql); if (!$result) { print mysql_error() . ' ERROR - Select note query failed! '; } if (mysql_num_rows($result) < 1) { print 'No notes in database.'; } print ''; print ''; while($row = mysql_fetch_array($result)) { print make_item_control(urlencode($row[item_name]),$row[item_name]); } print ''; print '
'; print ''; } ?>

[/php]

Suppose we want to delete comments that are obsolete. We can reuse the same code for printing checked items to delete selected items.

Example 3

[php]

<?php // example code for checkbox.txt // confirmed working: Friday, March 07, 2003 // Configuration information for connecting to database // Contains $db_name, $db_user, $db_pass, $db_host // for connection. // Enter your database host name here. $db_host = "YourDatabaseHost"; // Enter your database password here. $db_pass = "YourDatabasePassword"; // Enter your database user name here. $db_user = "YourDatabaseUsername"; // Enter the name of your database here. $db_name = "YourDatabaseName"; // Connect to database $db_conn = @mysql_pconnect($db_host, $db_user, $db_pass); // Check for database unavailable if (!$db_conn) { print "ERROR - failed to create connection: " . mysql_error(); } function make_item_control($value,$title) { $content = ' '.$title.''; return $content; } if($p_delete_checked) { // Process items // We substract one from the count because a for loop executes once // before incrementing. $n = count($item)-1; for($i = 0; $i <= $n; $i++) { $sql = "DELETE FROM note WHERE note_id = $item[$i];"; $result = mysql_db_query($db_name,$sql); if (!$result) { print mysql_error() . ' ERROR - Delete note query failed! '; } } } else { // list items // database query here $sql = "SELECT note_id,film_id,LEFT(text,32) AS item_name FROM note ORDER BY film_id ASC;"; $result = mysql_db_query($db_name,$sql); if (!$result || mysql_num_rows($result) < 1) { print ' ERROR - Select note query failed: ' .mysql_error(); } print ''; print ''; while($row = mysql_fetch_array($result)) { print make_item_control($row[note_id],$row[item_name]); } print ''; print '
'; print ''; } ?>

[/php]

Example Database Schema and Initial Values

The following is a database schema (a description of table structure) is provided so you can try the script for yourself. In addition there is SQL to populate the table with some initial values.

create table note (
	note_id INT(11) NOT NULL AUTO_INCREMENT,
	film_id INT(11) NOT NULL DEFAULT 0,
	item_name varchar(255) NOT NULL DEFAULT '',
	text TEXT  DEFAULT '',
	cite_title varchar(255) NOT NULL DEFAULT '',
	cite_link, varchar(255) NOT NULL DEFAULT '',
	
	PRIMARY KEY note_id (note_id),
	KEY item_id (film_id),
);

INSERT INTO note VALUES (100,16,'Lady Eastlake commented "It is now more than fifteen years ago that specimens of a new and mysterious art were first exhibited to our wondering gaze."','Eastlake, Photography','http://www.city-gallery.com/learning/');
INSERT INTO note VALUES (101,16,'"Not that
photographers flock especially to the metropolis; they are
wanted everywhere and found everywhere." provides ample evidence of the growth of photography in its earliest years.','Eastlake, Photography','http://www.city-gallery.com/learning/');
INSERT INTO note VALUES (102,16,'Lady Eastlake early on recognized the democratizing influence of photography, commenting that the pursuit "unites men of the most diverse lives, habits, and stations, so that whoever enters its ranks finds himself in a kind of republic..." a sentiment reminiscent of the early days of radio or the internet.','Eastlake, Photography','http://www.city-gallery.com/learning/');
INSERT INTO note VALUES (103,16,'Sir Charles Eastlake was first chairman of the Photographic Society, established in 1853, a newly instituted body for the support and recognition of the art of photography.','Eastlake, Photography','http://www.city-gallery.com/learning/');

Using While to Loop Through the Items

Although since its introduction in version 4 of PHP, foreach is the preferred way to iterate over an array, you may also use While to iterate over the checked items. For now, I leave that as an exercise for the reader.

All examples here are intended to generate output compatible with the XHTML 1.0 specification. See http://www.w3c.org for details.