In this tutorial we will add a dropdown box as a form so the user can select a specific year level and display only the year level specific information in the graph from the database.
Start by creating a form with a drop down list. We need to submit the form to the same file using this line:
form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
The whole form code is below:
form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Select Year level:<select name ="year">
<option value = 7>Year 7</option>
<option value = 8>Year 8</option>
</select>
<input type ="submit">
</form>
Check to see if form is submitted using isset()
If set run a sql with where condition - see below
If form has no value submitted - run a default sql statement
Code Snippet
//set empty arrays
$activities = [];
$counts = [];
//check to see if form has been submitted by using isset
if (isset($_REQUEST['year'])) {
$year = $_REQUEST["year"]; //store the value in variable if submitted
//query using the new variable value
$sql = "SELECT activity,count(activity) as count from sa_activities where year = ".$year. " group by activity order by activity";
}
else{
//run a default search
$sql = "SELECT activity,count(activity) as count from sa_activities group by activity order by activity";
}
//run sql query
$dbResult = mysqli_query($conn, $sql);
if(mysqli_num_rows($dbResult) > 0){
while($row = mysqli_fetch_assoc($dbResult)){
array_push($activities, $row["activity"]);
array_push($counts, $row["count"]);
}
}
else{
echo "No result";
}