Reputation: 29
I'm trying to filter a mysql table of results using an HTML select dropdown box. I have the filter working but then I want to have the option to display 'all' again but all I get is a blank set of results. Then when I refresh, it keeps the $POST value, I'd like that to be reset so 'all' of my results would show as default?? Cheers!
$sql = "SELECT * FROM books";
if(isset($_POST['value'])) {
$catvalue = $_POST['value'];
$sql = "SELECT * FROM books WHERE category = '$catvalue'";
} else if($catvalue == 'all'){
$sql = "SELECT * FROM books";
}
$rs_result = mysql_query ($sql);
Bellow my select filter form.
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post' name='form_filter' >
<select name="value">
<option value="All" selected="selected">All</option>
<option value="Design">Design</option>
<option value="Photography">Photograpy</option>
</select>
<br />
<input type='submit' value = 'Filter'>
</form>
Upvotes: 0
Views: 88
Reputation: 11942
$sql = "SELECT * FROM books";
if(isset($_POST['value']) and $_POST['value']!='All') {
$catvalue = addslashes($_POST['value']);
$sql = "SELECT * FROM books WHERE category = '$catvalue'";
}
$rs_result = mysql_query ($sql);
Refreshing the page will resend the same request. A way to avoid that is to use the "Post/Redirect/Get" pattern. It's well explained there : http://en.wikipedia.org/wiki/Post/Redirect/Get
Upvotes: 0
Reputation: 189
<option value="All" selected="selected">All</option>
You have used "All" with an uppercase "A". PHP is case sensitive so your php code should be like this:
if(isset($_POST['value']) and $_POST['value']!='All') {
$catvalue = addslashes($_POST['value']);
$sql = "SELECT * FROM books WHERE category = '$catvalue'";
} else {
$sql = "SELECT * FROM books";
}
$rs_result = mysql_query ($sql);
Upvotes: 1
Reputation: 12401
First of all, you are writing inline queries which is not a safe way to work. This can lead to SQL injection. Bind the parameters and pass them safely in to the query.
As far as you logic is concerned, you will have to do this
$sql = "SELECT * FROM books ";// should always fetch all the books
if(isset($_POST['value'])) {
$catvalue = $_POST['value'];
if($catvalue != 'All') // if value is not "all", filter it
$sql = "SELECT * FROM books WHERE category = '$catvalue'";
}
Upvotes: 0
Reputation: 866
$sql = "SELECT * FROM books";
if(isset($_POST['value'])) {
$catvalue = $_POST['value'];
if($catvalue != "All")
$sql = "SELECT * FROM books WHERE category = '$catvalue'";
}
$rs_result = mysql_query ($sql);
Upvotes: 0
Reputation: 1
$_POST['value']
always have a value on your code.
you may use the condition
if ( $_POST['value'] === 'All' ) {// select all}
Upvotes: 0