Forum Moderators: coopster
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.
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.