user225269
user225269

Reputation: 10893

How to check if a checkbox/ radio button is checked in php

I have this html code:

<tr>   
     <td><label><input type="text" name="id" class="DEPENDS ON info BEING student" id="example">ID</label></td>
    </tr>

      <tr>
    <td>
   <label> <input type="checkbox" name="yr" class="DEPENDS ON info BEING student"> Year</label>
       </td>
    </tr>

But I don't have any idea on how do I check this checkboxes if they are checked using php, and then output the corresponding data based on the values that are checked.

Please help, I'm thinking of something like this. But of course it won't work, because I don't know how to equate checkboxes in php if they are checked:

<?php



$con = mysql_connect("localhost","root","nitoryolai123$%^");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("school", $con);




$id =  mysql_real_escape_string($_POST['idnum']);


if($_POST['id'] == checked &  $_POST['yr'] ==checked ){
$result2 = mysql_query("SELECT * FROM student WHERE IDNO='$id'");


echo "<table border='1'>
<tr>
<th>IDNO</th>
<th>YEAR</th>



</tr>";

while($row = mysql_fetch_array($result2))
  {
   echo "<tr>";
   echo "<td>" . $row['IDNO'] . "</td>";
echo "<td>" . $row['YEAR'] . "</td>";


  echo "</tr>";
  }
echo "</table>";
}


mysql_close($con);
?> 

Upvotes: 1

Views: 8992

Answers (4)

AmmO
AmmO

Reputation: 1

If you include a hidden field, with the same name and the failure value that you want to show up in the post data, then when the checkbox does not return a value (it is unchecked), the hidden control on the form will.

echo '<form method="post"><input type="hidden" name="checkdata" value="0">\
    <input type="checkbox" name="checkdata" value="1">\
    <input name="submitbutton" type="submit"></form>\
    </body></html>';

if ($_POST['submitbutton']) {
    echo "Value:|".$_POST['checkdata']."|";
}

Upvotes: 0

zaf
zaf

Reputation: 23274

$_POST['yr'] == checked 

should be:

$_POST['yr'] == 'on'

The default for firefox is 'on', maybe different in other browsers. (Thanks to David)

Upvotes: 1

ZeissS
ZeissS

Reputation: 12135

You must give your checkboxes a value. This value gets send to the server, in case the checkbox is checked.

if ( $_POST['checkboxname'] == 'checkboxvalue' ) {

}

Since I see no form: To send the data to the server, you need a form around your input elements:

<form method="POST" action="myphpscript.php">
    YOUR CONTENT HERE
</form>

Upvotes: 3

Elie
Elie

Reputation: 7383

try the following:

if (isset($_POST['yr'])) { ... }

Upvotes: 1

Related Questions