Forum Moderators: coopster

Message Too Old, No Replies

Looped checkboxes inserted into MySQL

         

brut24

8:34 am on Jan 15, 2009 (gmt 0)

10+ Year Member



Hi Guys

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

cameraman

2:06 pm on Jan 15, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Using the array of possible values and the array of checked values, perform
array_diff() [php.net] to produce an array for the deletion.
Use array_intersect() [php.net] to produce an intermediate result that you then compare against existing records using array_diff(), and insert the result.

brut24

7:39 am on Jan 19, 2009 (gmt 0)

10+ Year Member



Thanks cameraman - how do you split the values in an array to update MySQL line by line?

enigma1

1:57 pm on Jan 20, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You could use the identifier with the array keys

<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.
}
}