Page 1 of 1

[php]check box dynamic name

Posted: Wed Jun 11, 2008 3:58 am
by natomiast
I have that form:

Code: Select all

 
<form method="POST">
<?php>
                   $j=1;
                   $i=1;
                      require "./konekt.inc";
                      $w= mysql_query ("SELECT nazwa_przedmiotu FROM przedmioty ORDER BY nazwa_przedmiotu");
                       echo '<table border="0">';     //dane pobrane z bazy wy?wietlane sa za pomoc? tablei
                            while($xx=mysql_fetch_assoc($w))
                             {
                              echo '<tr>';
                               $przedmiot_nazw[$j]=$xx["nazwa_przedmiotu"];
                            echo '<td width="10px"><input type="checkbox" name="'.$i.'" /"></td>';
                              echo '<td width="150px" ><b>'.$xx["nazwa_przedmiotu"].'</b></td>';
                              $j++;
                              $i++;
                              echo '</tr>';
                            }
                       echo'</table>';
?>
<input type="submit" value="Dodaj nauczyciela" name="dodaj_nauczyciel"  />
</form>
 
and action for form:

Code: Select all

 
    if($_POST["dodaj_nauczyciel"])
    {
                  generuj_id(5);
                 
                                 for($q=1;$q<30;$q++)
                                 {
                             echo $_POST[$q];
                                       if($_POST[$q]=="on")
                                       {
                                          mysql_query("INSERT INTO przedmioty_n(naucz_id, przedmiot) VALUES('".$id."','".$przedmiot_nazw[$q]."') ");
                                       }
                                }
      }
 
and the result for: "echo $_POST[$q];" is nothing. when i look at site source i see that first checbox have name="1", secend name="2".....I don't know why I con't view that names in "for" loop?
Thnx for any help :D

Re: [php]check box dynamic name

Posted: Wed Jun 11, 2008 5:00 am
by s.dot
Make your check box name like name[]

Then in $_POST..

Code: Select all

foreach ($_POST['name'] AS $name)
{
    //do something
}
The brackets [] make the check boxes into an array.

Re: [php]check box dynamic name

Posted: Wed Jun 11, 2008 5:02 am
by aceconcepts
If you're trying to receive multiple checkbox values then it's probably easier to submit the checkboxes as an array:

Code: Select all

 
<input type="checkbox" name="checkbox[]" />
 
The checkbox will get submitted as an array - so you can receive multiple values.

Deal with the checkbox array with a foreach loop

Code: Select all

 
$checkboxArr=$_POST['checkbox'];
 
if(!empty($checkboxArr) && is_array($checkboxArr))
{
   foreach($checkboxArr as $value)
   {
      //whatever
   }
}
 
hope it helps.