0

I am trying to make a search box using select option tag such that if I select 'all' in select option tag then each data of that column should be fetched.

Given below is my php code. Thanks

if(isset($_POST['submit'])) {
    $area = $_POST['city'];
    if(isset($_POST['work']!== 'all')) 
        {$work = $_POST['work']; } 
    else {$work = '*';} ;

    $sel2 = "SELECT * FROM `userdata` WHERE `area`='".$area."' AND `work`='".$work."'" ;  
  $res2 = mysqli_query($con,$sel2);
Regolith
  • 2,944
  • 9
  • 33
  • 50
fahad
  • 5
  • 4

2 Answers2

0

Since you're would like to fetch any and all work related data when work is equal to all, you don't have to mention that explicitly in the SQL query. Mention that only when you want to fetch specific work related data. So your code should be like this:

if(isset($_POST['submit'])) {
    $area = $_POST['city']; 
    $sel2 = "SELECT * FROM `userdata` WHERE `area`='".$area."'";
    if(isset($_POST['work']) && $_POST['work'] !== 'all') 
        $sel2 .= " AND `work`='".$_POST['work']."'";
    $res2 = mysqli_query($con,$sel2);

Sidenote: Learn about prepared statement because right now your query is susceptible to SQL injection attack. Also see how you can prevent SQL injection in PHP.

Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
0

Set up the variables like this

if(isset($_POST['submit'])) {
    $area = $_POST['city'];
    if(isset($_POST['work']!== 'all'))
$data=addslashes($_POST['work']); 
        {$work = "AND `work`='".$data."'";
} 
    else {$work = "";
}
///your query should be like this
$sel2 = "SELECT * FROM `userdata` WHERE `area`='".$area."' ".$work."";  
//////so if work is not specified then you don't need to select column WORK in the query. So it works as select * from userdata where area='".$area."';";

  $res2 = mysqli_query($con,$sel2);
in.k
  • 102
  • 2
  • 12