Reputation: 1
I am trying to make a query based on a get variable. I use the variable to specify which rows the query should find. When there is no get variable set, i want the query to get all rows.
Earlier in the code i set the $category variable to be either 1,2,3.
WHERE products.category = $category
The question: How do i make it get all the rows if no variable is set?
Upvotes: 0
Views: 121
Reputation: 3141
Ideally, you would add the where statement conditionally (if only the 1,2,3 categories exist), but if the category id's are fixed, you could try using;
if (!isset($category))
{
$category = "1,2,3";
}
WHERE products.category in ($category)
Upvotes: 0
Reputation: 24046
WHERE products.category =(case when $category IS not null
then $category else products.category end)
Upvotes: 0
Reputation: 15780
The best thing you can do is:
$wc = (isset($category)) ? "WHERE products.category = '$category'" : "";
$sql = "SELECT *
FROM products
" . $wc;
Upvotes: 1
Reputation: 650
Or
check if $category is set then
use products.category = $category
else 1
so the result will be either
WHERE products.category = $category
or
Where 1
Upvotes: 0
Reputation: 13465
dont add the where clause or just
WHERE products.category in (1,2,3)
Upvotes: 1
Reputation: 798606
Omit the WHERE
clause if the variable has no value.
Upvotes: 0