I want to write a single query instead of "if" statements which should be able to fetch filter applied data
The columns passed in "where" clause are:
usedBy,item_type,item_rarity,item_slot
filters={"hero":"Axe","type":"Weapon","rarity":"rare","slot":"hand","title":"Blood Shed"}
In above json all filters are applied and no null value so the simple sql query works great,for example
Select * from table where usedBy = 'Axe' and item_type = 'weapon' and item_rarity='rare' and item_slot = 'hand' and item_title = 'Blood shed'
But if anyone of them is null i wont get any result. for example :
filters={"hero":"Axe","type":"","rarity":"","slot":"","title":""}
So I want a query which can handle both the above requests at the same time.
Tried queries are(variables are used):
SELECT usedBy,item_type,item_name,item_slot,item_rarity from descriptions where usedBy = '$hero' and item_type ='$type' or item_type = '' and item_rarity='$rarity' or item_rarity ='' and item_slot='$slot' or item_slot = '' and item_name = '$title' or item_name=''
result for above query:
SELECT usedBy,item_type,item_name,item_slot,item_rarity from descriptions where usedBy = '$hero' and item_type ='$type' or item_type != '' and item_rarity='$rarity' or item_rarity !='' and item_slot='$slot' or item_slot != '' and item_name = '$title' or item_name !=''
Above query shown all the records of the table
Thanks in advance.
Try use of % sign with Like For example:
SELECT usedBy,item_type,item_name,item_slot,item_rarity from descriptions where usedBy LIke '%$hero%' and item_type LIKE '%$type%' ;
You must build your WHERE condition dynamically and put only variable that are not empty :
// build a list of conditions based on filters data
$conditions= array();
if($filters['hero'] != '')
$conditions[] = "usedBy = '" . $filters['hero'] . "'" ;
if($filters['type'] != '')
$conditions[] = "type = '" . $filters['type'] . "'" ;
....
// build the SQL query
$query = "SELECT usedBy,item_type,item_name,item_slot,item_rarity from descriptions where " . implode(' AND ', $conditions)
In this situation, make sure you validate and escape correctly your data to avoid SQL injections.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.