I am wanting to use a HTML options selector to filter the posts that my site will show by subject.
For example, if the user selects the subject Computer Science in the options, it will only show posts that have a 'post_subject' value of compSci.
However currently when I click the 'filter' button, it just shows all the posts from the database.
Here is an example of a post in the database:
Edit: after trying what was suggested in the comments, when filtered (other than for all subjects) it is returning nothing even though there are posts for each subject saved in the database
<div class="post">
<form name="writeForm" method="post">
<label for="subjectView">Choose a subject:</label>
<select name="subjectView" id="subjectView">
<optgroup label="SubjectsView">
<option value="all">All Subjects</option>
<option value="CompSci">CompSci</option>
<option value="Economics">Economics</option>
<option value="Maths">Maths</option>
<option value="Music">Music</option>
<option value="English">English</option>
</optgroup>
</select>
<p><input type="submit" value="Filter"></p>
</form>
<?php
if ($_POST['subjectView'] = 'all') {
$sql = "SELECT * FROM tblPosts ORDER BY post_date DESC";
$result = $connect->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<div class=\"post\"> <h2> Username: " . $row["user_name"] . "</h2></div>";
echo "<div class=\"postCont\"> <p>" . $row["post_contents"] . "</p></div>";
echo "<div class=\"post\"> <p>" . $row["post_date"] . "</p></div>";
}
} else {
echo "0 results";
}
} else {
$sql = "SELECT * FROM tblPosts ORDER BY post_date DESC WHERE post_subject = {$_POST['subjectView']}";
$result = $connect->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<div class=\"post\"> <h2> Username: " . $row["user_name"] . "</h2></div>";
echo "<div class=\"postCont\"> <p>" . $row["post_contents"] . "</p></div>";
echo "<div class=\"post\"> <p>" . $row["post_date"] . "</p></div>";
}
} else {
echo "0 results";
}
}
If you would like any clarification please ask :)