Hi,
Up till now I’ve processed sets of checkboxes/radio buttons that have been generated from database rows a particular way, but feel its restrictive in some cases and would like to know what others do.
Say I have a form for adding or editing a page with a list of checkboxes to allow certain groups access - Administrator, moderators and members for arguments sake. These groups are stored in a MySQL table, with the checkboxes generated using code like:
#Output group checkboxes
$list = '';
$result = mysql_query('SELECT * FROM groups');
while ($row = mysql_fetch_object($result)) {
$list .= '<input type="checkbox" name="groups[]" value="'.$row->groupID.'">';
}
echo $list;
I like to store the selected groups in a separate table to maintain relationships and for scalability, in this case the table contains 2 columns - pageID and groupID.
If I’m adding a page, my processing code tends to be like this:
#Add page details...
$id = mysql_insert_id();
#Add group permissions to database
$sql = array();
foreach ($_POST['groups'] as $groupID) {
$sql[] = "('$pageID', '$groupID')";
}
mysql_query("INSERT INTO page_groups (pageID, groupID) VALUES ".implode(',', $sql);
If I’m editing an existing page, I tend to delete all the groups entries for selected page then insert again:
#Edit page details...
$id = $_GET['id'];
#Remove all groups for selected page
mysql_query("DELETE FROM page_groups WHERE pageID = '$id'");
#Add group permissions to database
$sql = array();
foreach ($_POST['groups'] as $groupID) {
$sql[] = "('$pageID', '$groupID')";
}
mysql_query("INSERT INTO page_groups (pageID, groupID) VALUES ".implode(',', $sql);
#Optimise tables...
Note these PHP codes are simplified; my actual codes guard against SQL injections, etc.
They’ve been OK up till now, but they do have their flaws - being unable to identify changes when editing for one.
With all this in mind, what does anyone else do in situations like this? I have no doubts there are better approaches, so would appreciate some ideas.
Thanks in advance.