I have a dynamically generated table listing all users in a given group, and each user has a checkbox next to their name. The group admin may select/deselect these checkboxes to include/exclude a user. In the MySQL table, there is a status column for each user that is either a 0
or a 1
. I use hidden values to handle the unchecked status of boxes and POST the data as an array with each user's unique ID as the key.
So my POST data is an array that looks thus:
Array ( [105] => 1 [106] => 1 [107] => 0 [108] => 0 [109] => 1 )
Now, I need to update the db. Here is how I want the query to look:
INSERT INTO users (uid,status) VALUES (105,1),(106,1),(107,0),(108,0),(109,1)
ON DUPLICATE KEY UPDATE status=VALUES(status);
Of course, that doesn't INSERT anything, but it updates every row with a single query.
What I can't figure out is how to use the array to generate the query. Especially given that the number of users (the number of items in the array) will vary.
After additional research, it seems that my question may boil down to:
Is it possible to use implode
to turn this array:
Array ( [105] => 1 [106] => 1 [107] => 0 [108] => 0 [109] => 1 )
into this string:
(105,1),(106,1),(107,0),(108,0),(109,1)
with the flexibility to have more or fewer items in the array?
,
at then end of the values by checking ifloop_index + 1
equals thelength
of the array. – plalx Apr 13 '13 at 14:41foreach
array value. – David Apr 13 '13 at 15:05