简体   繁体   中英

PHP MySQL search with optional fields

I am trying to create a form that a user can enter information in and then search a table that matches this query. I want the information entered to be optional (not all fields need to be completed). I have the first 'if' working for just the floor and flatno but can not get the second 'if with the addition of the 'status' added to the query.

I know about the security issues in my code but only want to use this on an internal server as a guide for myself.

<?php


// if there is a value in the floor and flatno field then do this:
    if (!empty($_POST['Floor']) && (!empty($_POST['flatno']))) 
{
    require 'connectdb.php';
    $result = mysqli_query($con,"SELECT * FROM issuelog WHERE floor='$_POST[Floor]' AND flatnumber='$_POST[flatno]'");
}   

while($row = mysqli_fetch_array($result))
  {

include( "searchoutputform.php" );
  }

// second if - if there is something in the floor, flatno and status field then do this:

 elseif (!empty($_POST['Floor']) && (!empty($_POST['flatno'] && (!empty($_POST['status'])))))
{
    require 'connectdb.php';
    $result = mysqli_query($con,"SELECT * FROM issuelog WHERE floor='$_POST[Floor]' AND flatnumber='$_POST[flatno]' AND status='$_POST[status]'");
}   

while($row = mysqli_fetch_array($result))
  {

include( "searchoutputform.php" );
  }
endif;

// CLOSE CONNECTION TO DATABASE 
mysqli_close($con);
?>

Update: I have removed all of the requests to connect so there is only 1 now! I am getting the following error:

Parse error: syntax error, unexpected T_BOOLEAN_AND, expecting ') (this is based on the second if)

Hint

Your first if will always execute if both those values are there, your elseif will not execute then. Simply change your elseif to another if

if (!empty($_POST['Floor']) && !empty($_POST['flatno'] && !empty($_POST['status']))
{
//...
}   

Why so? Here's why

   if(1==1 && 2==2)
   {
      echo "first if";
   }
   elseif(1==1 && 2==2 && 3==3)
   {
     echo "this one will not execute even though the condition is true, due to elseif";
   }
   if(1==1 && 2==2 && 3==3)
   {
     echo "Now this one will work";
   }

That's one basic fix , but you should simplify the logic and build the query then append values to it if they are present.

And you have some extra parenthesis, and you have some extra includes :)

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