Been scratching my head on this for a while but hopefully someone can guide me:
I have a table (Standards) within my DB that has different foreign keys (Grade, Subject, Branch). On the user side, the user can enter a keyword and can further filter based on Grade (1st-12th) , Subject (Math, English, Science) ,or Branch(depends on Subject selection). This extra filtration is the problem that I am facing. What is a recommended approach for selecting data from the data based on the selections made?
Here is what I have when they don't select to filter the data:
function generalResult($keyword, $connection){
$sql = "SELECT standards_eng.Standard FROM standards_eng WHERE standards_eng LIKE '%".$keyword."%' ";
$query = $connection->query($sql);
if ($query->num_rows > 0) {
while ($row = $query->fetch_assoc()) {
echo '<p>' .$row['Standard']. '</p>';
}
}
}
Only solution I could come up with was If/else statements but that would be too many to count. For example:
if(Grade!== "" AND SUBJECT == "" AND BRANCH =="") {
//Selects data where Standard is like keyword AND Grade_ID is equal to value selected
} Else if (Grade!== "" AND SUBJECT !== "" AND BRANCH == "") {
//Selects data where Standard is like keyword Grade_ID and Subject is equal to value selected
}Else if{
...
}Else if{...}
I am not completely sure what you want, but if I am correct you want optional filters which can be left empty?
What i would do is create a filter and append/concatenate that string if an extra filter is needed. see underneath for an example.
$filter="WHERE standards_eng LIKE '%".keyword."%'";
if(Grade!==""){
$filter."AND Grade="value here";
}
if(SUBJECT!==""){
$filter."AND SUBJECT="value here";
}
if(BRANCH!==""){
$filter."AND BRACH="value here";
}
$sql = "SELECT standards_eng.Standard FROM standards_eng".$filter;
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.