Pages

Wednesday, June 16, 2021

PHP Dynamic Query

 if (isset("$_POST['submit']"))  

{  

    if ($search_by_id)  

    {  

        $query = " and id=' $search_by_id' ";  

    }  

    if ($search_by_name)  

    {  

        $query. = " and name like '%$search_by_name%' ";  

    }  

    if ($search_by_designation)  

    {  

        $query. = " and designation like '%$search_by_designation%' ";  

    }  

    if ($search_by_salary)   

    {  

        $query. = " and salary like '%$search_by_salary%'";  

    }  

    if ($search_by_role)   

    {  

        $query. = " and role like '%$search_by_role%' ";  

    }  

    if ($search_by_department)  

    {  

        $query. = " and id=' %$search_by_department%' ";  

    }  

}


Write your query like this,

mysql_query("Select * from tablename where 1=1 $query;");     

Here, "." operator in "$query." is used to concatinate $query itself. Suppose User enters the 5 in "search by id" and php developer in "search by role" fields and click submit . Then query will be:

Select * from tablename where 1=1 and id='5' and role like '%php developer%';     

Advantage of this format of query is that firstly it is fully dynamic for example suppose in future we have to add one or more fields you can simply add,

if($field_name){ $query.= " and column name like '%$field_name%'  "; }    

Feel Free to leave a comment for any doubt or questions.

No comments:

Post a Comment