Reputation: 23
I have 4 different MySQL query's and I want to be able to choose which one is used based on which radio button is clicked. I was wondering what would be the best way to do this?
<form action="">
<input type="radio" name="query1" value="">Rating<br>
<input type="radio" name="query2" value="">Genre<br>
<input type="radio" name="query3" value="">Year<br>
<input type="radio" name="query4" value="">Rating,Genre,Year
</form>
Do I store the query's on individual php pages and then call them using the radio button or ....?
The query's select movie info from a database and then order them by either rating, year, genre or all three.
Upvotes: 0
Views: 2360
Reputation: 5661
Radio buttons must have same name.
Without a method="post" the <form>
method will be "get" so the PHP would use $_GET
not $_POST
<form action="">
<input type="radio" name="query" value="1">Rating<br>
<input type="radio" name="query" value="2">Genre<br>
<input type="radio" name="query" value="3">Year<br>
<input type="radio" name="query" value="4">Rating,Genre,Year
</form>
I am not a big fan of using IF ELSE branching structures and avoid them whenever possible.
I prefer passing integer values to be used in arrays.
PHP
$q = intval($_GET['query']);
The intval()
will return a zero if ($_GET['query']
return no value.
$queries = array(
0 => $query4,
1 => $query1,
2 => $query2,
3 => $query3,
4 => $query4);
$sql = $queries[$q];
Upvotes: 1
Reputation: 74230
Set all your radio buttons to hold the same name attribute but with different values, then upon submit and choosing the desired radio button, query for what is matched.
<?php
if(isset($_POST['submit'])){
if(!isset($_POST['query'])){
echo "You chose nothing";
}
if($_POST['query'] == "Rating"){
// query for Rating
echo "Rating";
}
if($_POST['query'] == "Genre"){
// query for Genre
echo "Genre";
}
if($_POST['query'] == "Year"){
// query for Year
echo "Year";
}
if($_POST['query'] == "Rating,Genre,Year"){
// query for Rating,Genre,Year
echo "Rating,Genre,Year";
}
} // brace for if(isset($_POST['submit']))
?>
<form action="" method="post">
<input type="radio" name="query" value="Rating">Rating<br>
<input type="radio" name="query" value="Genre">Genre<br>
<input type="radio" name="query" value="Year">Year<br>
<input type="radio" name="query" value="Rating,Genre,Year">Rating,Genre,Year
<br>
<input type="submit" name="submit" value="Submit query">
</form>
This is at best, a basic example.
When using database-related code, remember to use mysqli
with prepared statements, or PDO with prepared statements, they're much safer.
Upvotes: 3