PHP-Mysql WHERE is empty AND returns results
I am not well versed in MYSQL, and I need some guidance here. I have read multiple MYSQL WHERE statement explanations, but have not found this exact issue. I have a table called studies that has fields like id, name, author, category, format and a few others.
I am building a filter with checkboxes to narrow down the query. I want to get all studies with a specific author AND category AND format. My problem comes when I build the query. If only the format is selected, the query returns empty because no author was selected. How do I get the results from the AND statements without the WHERE statement? Here is what I have so far...
"SELECT * FROM estudos WHERE subcategory='$subcategory' AND author='$author' AND format='$format'"
Answer
Solution:
If author is empty, don't include it in the query:
Alternatively, use OR instead of AND:
Answer
Solution:
You need to conditionally append the conditions based on whether the item was selected or not. I suggest something like:
Note that the
$params
part is only necessary if you are using a parameterized query like withPDO
(which you should be doing).Answer
Solution:
if only format is selected you should only query based on format like
if format and author is selected then
if all are selected then
You should run your query depending on the selection
Answer
Solution:
assign where condition to variable
for example
and append it to your query
Answer
Solution:
You could use he following code to generate the query
Answer
Solution:
Well what i would do is this:
I hope that works.
Answer
Solution:
I will suggest you to rewrite the query by using concatenation. Like:
$query= 'SELECT * FROM estudos WHERE 1';
if(isset($subcategory)) $query .= ' AND subcategory='.$subcategory;
if(isset($author)) $query .= ' AND author='.$author;
if(isset($format)) $query .= ' AND format='.$format;