Forum Moderators: coopster
When I just use checkboxes, it works just fine. I'm trying to associate another input field with each checkbox and keep them synchronized:
Pseudo code:
<checkbox name="date[]"><select name="time[]">
...Repeated multiple times
When I print_r the submitted $_POST, each time field gets submitted (i.e. Array ( [0] => 13:00:00 [1] => 23:00:00 [2] => [3] => [4] => 09:00:00 )) while only the checked boxes get submitted (i.e. Array ( [0] => 1 [1] => 2 [2] => 5 )). This messes up the key order unsynchronizes the two arrays.
The only ways I see this working are if all the checkboxes are checked (then every value gets submitted), or if the blank selects don't get submitted.
What's the best way to keep them synchronized?
Once they are synchronized, what's the best way to insert them in a db? Loop through both arrays? Combine the values from both into an associative array and loop through that?
Thanks!
I had thought of messing with the submitted select array and getting rid of blank entries and reindexing the array so it would match the submitted checkbox array, but if the user unchecks the box and leaves the time, it would mess up the count. I could use JS to disable the select box, but then I'm relying on JS to make my app work (which would easily break if a user had it disabled).
Ugh.
<checkbox name="info0[]"><select name="info0[]"> ...
<checkbox name="info1[]"><select name="info1[]"> ...
etc...
Here's what I did--there may be a more efficient way of doing it, but this works for now: (cleanText is a function I made for escaping quotes...)
...
foreach($_POST as $key => $value) {
${$key} = cleanText($value);
if (preg_match("/time/", $key)) {
if ($value != "") {
$actual_times[] = $key;
}
}
}
mysql_query("DELETE FROM classes_dates WHERE fk_class = $updateClass");
foreach ($actual_times as $real_time) {
$number = substr($real_time, -1);
$date = ${"date" . $number};
$time = ${"time" . $number};
if ($date != "") {
mysql_query("INSERT INTO classes_dates (fk_class, fk_date, class_time) VALUES ('$updateClass', '$date', '$time')");
}
}
...
What it does is loop through all the $_POST values to put all the date values that have a matching time in an array called actual_times, guaranteeing that every date saved has a matching time. I then loop through the actual_times array and do the sql based on that.