0

I have multiple checkboxes within a foreach loop and I need to keep the selected checkboxes checked after the form submission. The code is as below. Please help.

     <? $i=0;
        while ($row=mysql_fetch_array($result,MYSQL_ASSOC))
        {
          foreach($row=$val)
          {
            $id="chkbox".$i;
      ?>
          <input type="checkbox" name="chkbx" onclick ="func()" id="<?echo   $id;">? value="<?echo $val \n;?>" <? echo "$val";?>

Now where and how to include the checked property of the boxes..

2
  • Can you paste your while loop here ? Also, are you sure that you need to run foreach inside this while ? Commented Jul 8, 2015 at 7:00
  • 1
    The code is wrong. You are trying to convert $val from array to string. Commented Jul 8, 2015 at 7:03

1 Answer 1

1

You don't need foreach loop here

This can be done for checking multiple checkbox checked

  <?php
    $i=0;
    while ($row=mysql_fetch_array($result,MYSQL_ASSOC))
    {
        $checked = "";
        if($row['database_column_name']=$val){
            $checked = "checked";
        }
        echo '
         <input type="checkbox" name="chkbx" onclick ="func()" id="'.$id.'" value="'.$val.'" '.$checked.'>'.
          $val
         .'
        ';
    }
    ?>       

Works for me.

Sign up to request clarification or add additional context in comments.

2 Comments

Since he fetch array as associative, i guess the code should be like if($row['database_column_name'] = $val){ $checked = "checked"; }
@Meenesh Jain I need foreach loop to get the values from the array.. Sorry for the typo, I am using foreach($row as $val) and then retrieving the values one by one and inserting checkboxes for each.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.