FORM (radio control) in php

To analyze this control we will have an example:
Implement a form that requests the loading of two integers, one in each text. Have two radio-type controls that allow us to select whether we want to add or subtract the two values ​​entered:

<html>
<head>
<title>Problema</title>
</head>
<body>
<form action=”pagina2.php”
method=”post”>
Ingrese primer valor:
<input type=”text” name=”valor1″>
<br>
Ingrese segundo valor:
<input type=”text” name=”valor2″>
<br>
<input type=”radio” name=”radio1″ value=”suma”>sumar
<br>
<input type=”radio” name=”radio1″ value=”resta”>restar
<br>
<input type=”submit” name=”operar”>
</form>
</body>
</html>

It is important to note that this is again a pure HTML file, which has no PHP code.
The entry of the two numbers is carried out in two controls
<input type = “text” name = “value1”> <input type = “text” name = “value2”> It is important to note that each text has a DIFFERENT name.
To select the type of operation to carry out, we have two radio-type controls:
<input type = “radio” name = “radio1” value = “add”> add <br> <input type = “radio” name = “radio1” value = “subtract”> subtract It is important to note that the two controls have the Same name. This is necessary so that the browser knows that the two controls are related (remember that when one selects a radio, the other must be deselected)

From the other page we will access the value of the selected control.

Finally we have a submit type control for sending the form data.
The code of the page that processes the form, called: “page2.php” (the one that we indicate in the FORM mark of the form) is:

<html>
<head>
<title>Problema</title>
</head>
<body>
<?php
if ($_REQUEST[‘radio1’]==”suma”)
{
$suma=$_REQUEST[‘valor1’] + $_REQUEST[‘valor2’];
echo “La suma es:”.$suma;
}
else
{
if ($_REQUEST[‘radio1’]==”resta”)
{
$resta=$_REQUEST[‘valor1’] – $_REQUEST[‘valor2’];
echo “La resta es:”.$resta;
}
}
?>
</body>
</html>

The associative vector $ _REQUEST has three components: $ _REQUEST [‘radio1’] $ _REQUEST [‘value1’] $ _REQUEST [‘value2’] In the component $ _REQUEST [‘radio1’] it stores the string “addition” or “subtraction” depending on which was selected in the form.
With two if we verify which operation is selected and proceed to perform it:

if ($_REQUEST[‘radio1’]==”suma”)
{
$suma=$_REQUEST[‘valor1’] + $_REQUEST[‘valor2’];
echo “La suma es:”.$suma;
.
.

This article was written by admin

Leave a Reply