Home > Enterprise >  How can I know which radio button is selected in php?
How can I know which radio button is selected in php?

Time:05-22

This is my radio form in html:

<form action="form2.php" method="POST">
<label><input type="radio" name="select" value="insert"> Insert </label>
<label><input type="radio" name="select" value="remove"> Remove </label>
</form>

How can I check which of 2 radio is chosen in php file (connected with database). For example, if is selected insert then add new member. If selected remove then remove a member.

$select = $_REQUEST['select'];
echo $select;

It returns "on" not insert/Insert nor remove/Remove

CodePudding user response:

Add a value attribute to your radio inputs:

<form action="form2.php" method="POST">
<label><input type="radio" name="select" value="insert"> Insert</label>
<label><input type="radio" name="select" value="remove"> Remove</label>
<button>submit</button>
</form>

I also added a submit button.

If form2.php contains

<?php
echo $_REQUEST['select'];

or

<?php
echo $_POST['select'];

it will print out insert or remove after you submit the form depending on which radio you selected.

More on radio inputs: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio

CodePudding user response:

This is very simple. Just check the value of your post data.

<?php
if(isset($_REQUEST['select'])){
  switch ($_REQUEST['select']) {
      case 'insert':
        // Insert new

        break;
      
      case 'remove':
        // Remove
        break;
    }  
}
  • Related