Noobster Noobster - 10 months ago 42
PHP Question

php - How to insert looped value of checkbox into a single mysql_query

I have here a looped value of checkboxes let's assume I have 3 increments

<?php foreach ($times as $time) { ?>
<input type="checkbox" name="b" id="b1" value=" <?php echo $time->format('h:i a'), '-', $time->add($interval)->format('h:i a'); ?>">
<?php } ?>

In the
it display 3 checkboxes that has different value.
Now for example i checked 2 boxes. The query must run twice? Or better yet, the 2 checked value must be inserted to the db.

$b = $_POST['b'];
$ins = mysql_query("INSERT INTO ehr_schedule3(`sched3_time) VALUES('$b')");

How can I do that?


All your checkboxes have the same name, so $_POST['b'] will just get the value of the last one. To get multiple values, you need to use an array-style name:

<?php foreach ($times as $time) { ?>
<input type="checkbox" name="b[]" value="<?php echo $time->format('h:i a'), '-', $time->add($interval)->format('h:i a'); ?>">
<?php } ?>

Then $_POST['b'] will be an array of all the values.

foreach ($_POST['b'] as $b) {
    $b = mysql_real_escape_string($b);
    $ins = mysql_query("INSERT INTO ehr_schedule3(`sched3_time) VALUES('$b')");

I also took out id="b1" because you shouldn't have multiple elements with the same ID. If you really need the inputs to have IDs (why?), you'll need to give them different ones, perhaps by using the array index as part of the ID.