This may turn out to be little more than a rant, but bear with me here.
I have had a lot of experience working with checkboxes lately, and I've realized a few basic facts:
1) Checkboxes only POST when they are checked. That means you either have to check whether the checkbox posted, or you have to ignore the non-posting checkboxes.
2) Checkboxes can be extremely unwieldy to work with in queries, especially if they are POSTed as an array.
With that in mind, I had to make a major shift in my thinking. Assuming the checkbox values are eventually stored in a database, I had to design with the goal in mind. In other words, my checkboxes are named exactly as they are stored in the database. Everything else become infinitely easier from there.
The emphasis then gets shifted to query building rather than sifting through POST values. The following code shows how I build the query string:
// Initialize two parts of the query string:
$query_left = "INSERT INTO table_name (";
$query_right = ") VALUES (";
// Add the POST values:
foreach($_POST as $key => $value)
{
// "Submit" is usually your last field on an HTML form, so break:
if($key == 'submit') break;
// If you are on the last field before submit, you want to skip the comma in the query string:
if($key == '{second to last field}')
{
$query_left .= $key;
// Separate out the numeric fields from the strings:
if(is_numeric($value))
{
$query_right .= $value;
}
else
{
// Strings will need quotes around them for the query:
$query_right .= "\"".$value."\"";
}
}
else
{
// Include the commas:
$query_left .= $key.",";
// Separate out the numeric fields from the strings:
if(is_numeric($value))
{
$query_right .= $value.",";
}
else
{
$query_right .= "\"".$value."\", ";
}
}
}
// Now cap off the ends:
$query_left .= ")";
$query_right .= ")";
// And put it together:
$query = $query_left.$query_right;
// Admire your finished query string, fully ready for database execution!
echo $query;
Then you can either store this query in a SESSION variable, or use it.
That leaves the question about maintining POST data without updating the database. The easiest thing (to me) is just to update the database, but hold the primary key in a session variable so you can delete it later if the user doesn't commit the data. That way if the user wants to go back and change something, you can query the database for the appropriate form values. So for example:
if(isset($_SESSION['primary_key']))
{
$pk = $_SESSION['primary_key'];
// Query the database:
$query = "SELECT * FROM table WHERE primary_key = $pk";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
extract $row;
}
Then your HTML would include something like:
<input type="checkbox" name="field1" value="1"<?php echo isset($field1)?" checked":""; ?>>