Forum Moderators: coopster

Message Too Old, No Replies

Comparing PHP array from checkbox to MySQL table

Checkboxes, PHP arrays, and MySQL table

         

mattsplatw

2:04 am on Aug 26, 2007 (gmt 0)

10+ Year Member



Hi -

My problem involves updating a MySQL table using checkbox input. I'm relatively new to both PHP and MySQL so I'm looking for a little direction on the smartest way to accomplish my goal.

When a user goes to a project page, they are able to categorize their project by area. The user checks a series of checkboxes and the results are stored in an arrays called $category_ids. I'll called the project id $project_id.

What I want to do is compare the array $category_ids to entries in a MySQL table for $project_id. Then I want to add the links that aren't already in the table and delete the ones that need to be deleted. The table has these fields:

projects_cat_link (table)
----------------------
category_id ¦ project_id (fields)

Does anyone have any tips on how to do this? I've gathered that maybe there's a way to get the MySQL data into a similarly formed array and then use functions like array_diff to compare. But then I'm not sure how to use the comparison in a MySQL query to add/edit/delete the links.

Any help would be appreciated.

mattsplatw

3:48 am on Aug 26, 2007 (gmt 0)

10+ Year Member



I seem to have figured out a pretty good way to do this...

For the $project_id of interest, I load the MySQL table data into an array called $mysql_cats. I then post it along with the $category_ids output from the checkboxes.

Then I use array_diff to give me the links that should be added and deleted:
$add_cats = array_diff($cats,$mysql_cats);
$delete_cats = array_diff($mysql_cats,$cats);

And finally, I do a foreach loop through both $add_cats and $delete_cats and perform the appropriate MYSQL DELETE and INSERT queries. It seems to work pretty well.

Maybe this will help someone else.

jatar_k

4:01 am on Aug 26, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld mattsplatw,

I promise we actually help people figure stuff out once in a while. ;)