开发者

how to retrieve checked values in php

I am a newbie in php. I have a form with multiple checkbox values. I wanna retrieve the checked values and diplay these values on other php form.

Below is the code which works perfectly fine if we add the checkboxes without while loop. But when added through while loop I am not able to fetch the selected items.

xyzhtml.php(html form)

<?PHP
        require ("DBConnect.php");
        $selectQuery =mysql_query( "SELECT * FROM fruits where approved = 0");
        while($row = mysql_fetch_array($selectQuery))
        {
          $fruit_name = $row['fruit_name'];
           echo "<input type=\"checkbox\" name=\"things[]\" value=\"$fruit_name\">";
           echo "<br>";
        }
        ?>

 On click of submi开发者_Python百科t I call other php clled "xyz.php".
    Below is the code used in it.

 <?php

  $checkBox = $_POST['things'];

  echo $checkBox[0];
  for($i=0; $i<sizeof($checkBox); $i++){

  echo($checkBox[$i]);


  }

  ?>

Please help. Thanks in advance.


two things to check:

  1. are you getting right values from the MySQL SELECT statement (check your HTML for empty checkboxes values and check your MySQL database for fruits that have approved field set to 0 to see if there are any)

  2. when you don't tick a checkbox and submit the form, unticked checkboxes' values do not get submitted - have you thought about that?


Use foreach to record $_POST['things']

if (!empty($_POST['things'])) {
   foreach ($_POST['things'] as $value) {
     echo "the value are: ".$value;
   }
}

Note: teh $_POST['things'] not $_POST['things[]']


I think your code should work, but it won't display anything if no checkboxes are selected.

I would however remove the explicit echo $checkbox[0] (unless this is for testing purposes).

Try a print_r($checkbox) to see what's actually in that array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜