Checking set values (radio buttons) in PHP

This tutorial explains how to use radio buttons in forms and check set values in PHP to ensure that the user has entered data in the form. Watch the video below and then scroll down to see the sample code.

Sample PHP code:

Step 1: Create a PHP file (eg. form.php) which contains a form with radio buttons by copying the following code. This example will quiz the user on the capital city of Australia.

<html>
<head>
  <title>Form that checks set values</title>
</head>
<body>
  <form action="action_handler.php" method="POST">
    <p>What is the capital city of Australia?</p>
    <input type="radio" name="capital" value="Sydney"> Sydney<br>
    <input type="radio" name="capital" value="Canberra"> Canberra<br>
    <input type="radio" name="capital" value="Melbourne"> Melbourne
    <p><input type="submit"></p>
  </form>
</body>
</html>

Step 2: Create a separate PHP file called action_handler.php and copy the following code into it. This file will handle the form data.

<?php
  if(isset($_POST['capital'])){
    $capital = $_POST['capital'];
  }
  else{
    $capital = NULL;
  }

  if($capital != NULL){
    if($capital != "Canberra"){
      echo "$capital is incorrect";
    }
    else{
      echo "$capital is correct";
    }
  }
  else{
    echo "You must select an answer";
  }
?>