简体   繁体   中英

How do I use the checkbox type of input in PHP correctly

I want the code below to show all the selected checkboxes and to have a limit of 2 checkboxes ticked.

Input

<form method="post" action="Outputofinfo.php">
   <b style="font-size:19px ; color: #7a1ac4; font: Arial,tahoma,sans-serif; ">Favourite Movie Genre:</b><br>
   
    <input type="checkbox" name="mg" value="Romance">
 <label for="mg1"> Romance</label><br>
 <input type="checkbox" name="mg" value="Comedy">
 <label for="mg2"> Comedy</label><br>
 <input type="checkbox" name="mg" value="Horror">
 <label for="mg3"> Horror</label><br>
 <input type="checkbox" name="mg" value="Action">
 <label for="mg4"> Action</label><br>
 <input type="checkbox" name="mg" value="Fiction">
 <label for="mg5"> Fiction</label><br>

 <input type="submit">
</form>

output

$fmg = $_POST['mg'];
<div style ='font:21px Arial,tahoma,sans-serif;color:#7a1ac4'>
    <b>Favourite Movie Genre:</b>
    <?php echo $fmg; ?>
</div>

Adding [] to the end of name attribute like name=mg[] makes it send an array of values to the server. You can simply access the array on the server-side. For example you can access first element of it like: $_POST['mg'][0] . By using a foreach you can access all of the selected checkboxes. Or you can use something like this:

$fmg = implode(", ", $_POST['mg']);

and show $fmg to the user as you want. Your code will be:

<form method="post" action="Outputofinfo.php">
   <b style="font-size:19px ; color: #7a1ac4; font: Arial,tahoma,sans-serif; ">Favourite Movie Genre:</b><br>
   
    <input type="checkbox" name="mg[]" value="Romance">
 <label for="mg1"> Romance</label><br>
 <input type="checkbox" name="mg[]" value="Comedy">
 <label for="mg2"> Comedy</label><br>
 <input type="checkbox" name="mg[]" value="Horror">
 <label for="mg3"> Horror</label><br>
 <input type="checkbox" name="mg[]" value="Action">
 <label for="mg4"> Action</label><br>
 <input type="checkbox" name="mg[]" value="Fiction">
 <label for="mg5"> Fiction</label><br>

 <input type="submit">
</form>

output:

$fmg = implode(",",$_POST['mg']);
<div style ='font:21px Arial,tahoma,sans-serif;color:#7a1ac4'>
    <b>Favourite Movie Genre:</b>
    <?php echo $fmg; ?>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM