CodeDezk CodeDezk - 1 month ago 8
MySQL Question

MYSQL select query with multiple conditions and if input not null

I have to search a table with multiple condition with multiple input value, and input value should include in query only when if it is not null.

The php receives the variable like

$username=$_GET["username"];
$uniqueid=$_GET["uniqueid"];
$tag=$_GET["tag"];
$location=$_GET["location"];


the variable may be null or with some string, I want to avoid the variable from query which is null.

Suppose no variable is null then my query should be

select NAME from TABLE_NAME where USERNAME=$username AND INIQUEID=$uniqueid AND TAG=$tag AND LOCATION=$location;


And in-case
$username
is null then

select NAME from TABLE_NAME where INIQUEID=$uniqueid AND TAG=$tag AND LOCATION=$location;


So I need to create different query for each condition, or is there any way exist do all together?

Answer

Check this,

<?php

$query = "SELECT NAME  FROM TABLE_NAME WHERE ";

$flag = 0;
if(!empty($username)){
   $query .= " USERNAME='$username' ";
   $flag = 1;
}
if(!empty($uniqueid)){
   if($flag == 1){
        $query .= " AND ";
   }
   $query .= " INIQUEID='$uniqueid' ";
   $flag = 1;
}
if(!empty($tag)){
   if($flag == 1){
        $query .= " AND ";
   }    
   $query .= " TAG='$tag' ";
   $flag = 1;
}
if(!empty($location)){
   if($flag == 1){
        $query .= " AND ";
   }     
   $query .= " LOCATION='$location' ";
}

?>