1

First of let me explain my project. In my project i have many search parameters such as First Name , Last Name , Address , Valid ID. These are the parameters i am taking from users to search the database. I am giving the users the flexibility to search the database with 4 parameters or 3 or 2 or 1 depending on the user. Increasing the search parameters decreases the margin of the search. Currently the way i search the database is by checking each parameters. I am having all the possibility or combination of all 4 parameters.

4 combinations of using 1 parameter

6 combination of using 2 parameters

4 combinations of using 3 parameter

1 for using 4 parameters

giving me a total of 15 if statements. Is there a cleaner more short way to make it?I am asking this because now i am working with making 7 parameters and the combinations is really big.

In code it would look like this

if(!empty(fname)){}
else if(!empty(lname)){}
else if(!empty(address)){}
else if(!empty(vid)){}
else if(!empty(fname) && !empty(lname)){}
else if(!empty(fname) && !empty(address)){}
else if(!empty(fname) && !empty(vid)){}
else if(!empty(address) && !empty(lname)){}
else if(!empty(vid) && !empty(lname)){}
else if(!empty(adress) && !empty(vid)){}
else if(!empty(fname) && !empty(lname) && !empty(address)){}
else if(!empty(fname) && !empty(lname) && !empty(vid)){}
else if(!empty(fname) && !empty(add) && !empty(vid)){}
else if(!empty(lname) && !empty(add) && !empty(vid)){}
else if(!empty(fname) && !empty(add) && !empty(vid) && !empty(lname)){}
3
  • indexing is the best way to search the data from database.You can add the primary key in your table Commented Feb 27, 2015 at 4:14
  • Can you edit post and add 7 parameters combinations example. Commented Feb 27, 2015 at 4:14
  • for seven example( 1 , 2, 3, 4, 5, 6, 7 ) 7 parameter = 1 combination ; 6p = 7c; 5p = 21c; 4p = 35c; 3p = 35c; 2p = 21c; 1p = 7c; total of 127 combinations then i would have to make 127 if statements Commented Feb 27, 2015 at 4:31

3 Answers 3

1
Try this code.

 <?php
    //parameters
    $First_Name="val1";
    $Last_Name="val2";
    $Address="val3";
    $Valid_ID="";
    $Age="val5";
    $Gender="val6";
    $Dob="val7";
    //push the parameter names to array
    $parms=array("First_Name","Last_Name","Address","Valid_ID","Age","Gender","Dob");
    //iterate parameter name
    foreach($parms as $s){
        //check whether the parameter value is not empty
         if(!empty(${$s})){
            //your sql where condition
          echo $s.'='.${$s}."<br>"; //here it will print only non empty param and values
          }
    }
 ?>
Sign up to request clarification or add additional context in comments.

1 Comment

Sir how would you deal with the if in this example?i mean how would you make the select statements
0

Write select query in a variable then append it with where conditions like given below then append (and/or) key word until before last parameter.

   $qry="select * from table where ";
    $i=0;
    $paramcount=0;
     $cond=array(); //condition paramters
    foreach($parms as $c){
         if(!empty(${$c})){
             $paramcount++; //non empty parameters count
             $cond[]= $c.'="'.${$c}.'"';    //condition parameters 
      }
    }
    foreach($cond as $s){
        if($i<$paramcount-1){
        $qry=$qry.$s." and "; //appending add/or keyword with sql query
    }
    else{
        $qry=$qry.$s; //if last parameter means append parameter without and/or keyword
    }
        $i++;
    }

   echo "Final Query is --><br> ".$qry;

1 Comment

can you edit answer like the one in my question i cant make it run i cant understand it.
0

Do you really need to control each combination state. If so using flag variables, bitwise operators and case statement can be more handy. Even so i recommend to change your algoritm. Using something more flexible. Such as developing a class handles all the logic, setting all params a default value and creating the SQL Query string dynamically.

Here is my code from a project similiar to yours. I was used DB Query Builder class on laravel.

class recSQL {

    protected $recFinder;

    // $search_criteria is an instance of a class that 
    // contains default paramaters and overriden by user input parameters

    public function findRec($search_criteria, $sort_criteria)
    {
        $this->recFinder = DB::table('myTable')
            ->join('users', 'recs.user_id', '=', 'users.id')
            ->join('placelar', 'recs.place_id', '=', 'placelar.id')
            ->join('nested_categoris', 'recs.cat_id', '=', 'category.id')
            ->select(   'recs.user_id', 
                        'users.name as user_name',
                        'recs.id', 
                        'recs.baslik', 
                        'recs.price', 
                        'recs.durum_id', 
                        'category.name as category_name',
                        'recs.updated_at as date',
                        'placelar.ad as place');
        $this->applySearchCriteria($search_criteria);
        $this->applySortCriteria($sort_criteria);
        return $this->recFinder->paginate(3);
    }



    protected function applySearchCriteria($search_criteria)
        {
            // the parameters that allways in query
            $this->recFinder->where('recs.price', '<', $search_criteria->max_price());
            $this->recFinder->where('recs.price', '>', $search_criteria->min_price());
            $this->recFinder->where('recs.durum_id', '=', $search_criteria->durum());
            // the parameters if exists add to query
            if($search_criteria->place()) {
               $this->recFinder->where('recs.place_id','=', $search_criteria->place());}
            if($search_criteria->size()) {
               $this->recFinder->where('recs.size_id','=', $search_criteria->size());}
            if ($search_criteria->category()>0) {
                $secilen_category = Nestedcategory::where('id',$search_criteria->category())->first();
                $this->recFinder->where('category.lft','>=' , $secilen_category->lft);
                $this->recFinder->where('category.rgt','<=' , $secilen_category->rgt);
            }
        }



    protected function applySortCriteria($sort_criteria)
        {
            switch ($sort_criteria)
            {
                case Sirala::$dateasc:
                    $this->recFinder->orderBy('recs.updated_at', 'asc');
                    break;
                case Sirala::$datedesc:
                    $this->recFinder->orderBy('recs.updated_at', 'desc');
                    break;
                case Sirala::$priceasc:
                    $this->recFinder->orderBy('recs.price', 'asc');
                    break;
                case Sirala::$pricedesc:
                    $this->recFinder->orderBy('recs.price', 'desc');
                    break;
                // default:
                   // handle error;
            }
        }

}

I wish this helps you.

1 Comment

I dont have to control the combination i just need to cover all possible combinations i will check this code when i come back to work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.