简体   繁体   中英

Advanced Search Function with PHP

currently I have a form that allows users to fill in 3 input fields. 3 of them are text fields (title, author and ISBN) and 1 of it is a select option (categories).

What I would like to achieve is to allow users to fill in any number of the 4 fields, and return the respected values. This means that if users fills in 2 input fields, there will be 2 conditions to check in the backend. 3 inputs filled means 3 conditions.

What I have currenly is this (an example, not the actual code itself):

    if($title == $allMyArray["title"]){
        array_push($returningResult, $allMyArray);
    }else if($author == $allMyArray["author"]){
        array_push($returningResult, $allMyArray);
    }else if($ISBN == $allMyArray["ISBN"]){
        array_push($returningResult, $allMyArray);
    }else if($categoreis== $allMyArray["categories"]){
        array_push($returningResult, $allMyArray);
    }else{
        echo "nothing";
    }

This set of code works when I only fill in one specific field. For example if I fill in only the author input, and leave the other 3 options blank, I will be returned wwith the values I want. However, if I attempt to fill in 2 or more fields at once, the returned value is incorrect.

So how else can I come up with an if else statement that will check which fields are filled, and set the conditions correctly based on the inputted fields?

Thank you all for your help in advanced! Much appreciated! :)

Changing to below code will work. The problem is when you use ELSE you are limiting your conditional statements to one result only.

Optionally, you can use switch/case statement if you find IF dirty.

But it may produce duplicates, so you need to work this out. (i dont know your code, it is just an assumption)

$atLeast1Result = false;
if($title == $allMyArray["title"]){
    array_push($returningResult, $allMyArray);
    $atLeast1Result = true;
}
if($author == $allMyArray["author"]){
    array_push($returningResult, $allMyArray);
    $atLeast1Result = true;
} 
if($ISBN == $allMyArray["ISBN"]){
    array_push($returningResult, $allMyArray);
    $atLeast1Result = true;
}
if($categoreis== $allMyArray["categories"]){
    array_push($returningResult, $allMyArray);
    $atLeast1Result = true;
}
if(!$atLeast1Result ) {
    echo "nothing";
} else {
    $returningResult = array_unique($returningResult); // this might now work on all versions, as i dont know what this array is.
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM