php checkbox problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
urboyfriend
Forum Newbie
Posts: 11
Joined: Tue Sep 06, 2011 6:29 pm

php checkbox problem

Post by urboyfriend »

passing a value from a checkbox ton another page is simple if it is only one

Code: Select all

#page1.html

<html>
  <head>



  </head>
  <body>


  <table border='0' width='50%' cellspacing='0' cellpadding='0' >
  <form name=form1 method=post  action="page2.php">
 
  
  
  <tr>
  <td><b>Skills set</b></td>
  <td>&nbsp;</td>
  <td>
  <input type=checkbox name=scripts value='Java'>Java <br>
  <br>
  </td>
  </tr>
  
  <tr><td align=center >
  <input type=submit value=Submit> 
  <input type=reset value=Reset></td></tr>
  
  </form> 
  </table>


  </body>
</html>

Code: Select all

#page2.php
<?PHP


if ($_SERVER['REQUEST_METHOD'] == 'POST') {

if (isset($_POST['scripts'])) {
 
$cb = $_POST['scripts'];

print $cb;
   
} 
else{
print "you have'nt checked anything!";
}
}
?>

however, what if the checkboxes are dynamically generated with the same name? and we need to pass all the values that has been checked to the other page?

Code: Select all

<ipnut type=checkbox name=scripts value='Java'>
<input type=checkbox name=scripts value='CSS'>
<input type=checkbox name=scripts value='PHP'>
<input type=checkbox name=scripts value='HTML'>
<input type=checkbox name=scripts value='XML>
KCAstroTech
Forum Commoner
Posts: 33
Joined: Sat Aug 27, 2011 11:16 pm

Re: php checkbox problem

Post by KCAstroTech »

You need to make the name an array by putting [] after it, otherwise only the last checked value will be passed. By using an array it will pass all checked values:

Code: Select all

<ipnut type=checkbox name="scripts[]" value='Java'>
<input type=checkbox name="scripts[]" value='CSS'>
<input type=checkbox name="scripts[]" value='PHP'>
...
urboyfriend
Forum Newbie
Posts: 11
Joined: Tue Sep 06, 2011 6:29 pm

Re: php checkbox problem

Post by urboyfriend »

thanks, solved the problem
Post Reply