Forum Moderators: coopster
I have spent hours trying to get this working this morning and am now asking for help!
I have a form that has a variable number of checkboxes depending on how many records exist in the database, the output would be something like:
<input type="checkbox" name="word[]" value="3" /> 3
<input type="checkbox" name="word[]" value="4" checked /> 4
<input type="checkbox" name="word[]" value="9" /> 9
<input type="checkbox" name="word[]" value="22" /> 22
Some of them might be checked (ie. the user already has a link to it). By checking something they want to link to it, by unchecking they want to unlink.
When I submit the form I want to do a few things:
1. if a checkbox was checked and is now unchecked i want to delete that record from MySQL (possibly multiple checkboxes)
A record would consist of UserID and WordID
2. if a checkbox wasn't checked and is now checked I want to insert that record int MySQL (possibly multiple checkboxes)
Sounds simple enough but I have not managed to get anything working. I tried loading the posted results into an array and working with them like that but i didn't mange to get it working.
Any help would really be appreciated!
thanks
<input type="checkbox" name="word[3]" value="3" /> 3
Then during form processing
// Get all checkboxes records from the dbase as the form that displays them does "select records from table where....". The store it into another array lets say db_array holds the identifiers as keys.
if( isset($_POST['word']) && is_array($_POST['word']) ) {
foreach( $_POST['word'] as $key => $value ) {
// validate against the dbase records
if( !isset(db_array[$key]) ) continue;
// If we are here it means the checkbox is ticked
// Do something like insert.
........
// Cleanup from original array
unset(db_array[$key]);
}
foreach( db_array as $key => $value ) {
// Delete the records here or you could do an implode on the remaining keys instead of the foreach and use a single query to delete.
}
}