Do not append a radio-button or query-string value directly to SQL. Validate it against the small set of accepted values and bind it to a prepared statement.
<?php
$allowed = ['male', 'female'];
$sex = $_GET['type'] ?? '';
if (!in_array($sex, $allowed, true)) {
$sex = 'male';
}
$stmt = $pdo->prepare('SELECT id, name FROM student WHERE sex = :sex ORDER BY name');
$stmt->execute(['sex' => $sex]);
?>
The browser can submit the selected value normally or use fetch() if the list should update without a full page reload.
<script type="text/javascript">
function reload()
{
for(var i=0; i < document.form1.type.length; i++){
if(document.form1.type[i].checked)
var val=document.form1.type[i].value
}
self.location='test.php?type=' + val ;
}
</script>
We will receive the value and use them in our SQL query by adding one WHERE clause to restrict the records returned from the table. Here is how the value is received from query string and used for SQL query.
<?Php
require "config.php"; // database connection here
$tp=$_GET['type']; // getting the value from query string
if(strlen($tp) > 1){$sql="SELECT name,id FROM student where sex='$tp'";}
else{$sql="SELECT name,id FROM student";}
echo $sql;
echo "<br>";
echo "<form name=form1 method=post action=test.php>";
echo "<select name=student value=''>Student Name</option>"; // printing the list box select command
foreach ($dbo->query($sql) as $row){//Array or records stored in $row
echo "<option value=$row[id]>$row[name]</option>";
/* Option values are added by looping through the array */
} echo "</select>";// Closing of list box
echo "
<b>Type</b>
<input type=radio name=type value='male' onclick="reload()";>Male
<input type=radio name=type value='female' onclick="reload()";>Female
<input type=submit value=Submit> </form>";
?>
Demo of list box population with period button is here
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.