0

I know I am supposed to apply prepared statement, but at this stage I just want to get clear about the basic for multiple search criteria.

I have 3 criteria for users to query, if users input 3 criteria conditions then my code returns the correct result. But when the user only input 1 criteria then my code return records not found.

I have tried to include (is set) in the criteria but I find conflicting with (is set) in summit button.

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

$status = $_POST['status'];
$area = $_POST['area'];
$address = $_POST['address'];

if($status != "" OR $area != "" OR $address != ""){
$query = "SELECT * FROM `tbl_name` WHERE address LIKE '%".$address."%' 
AND status LIKE '%".$status."%' AND area = '$area' ";
}

I expect users can get the results either input in the all 3 search criteria, or only any 2 criteria or only any 1 criteria.

But my case only input all 3 only can return correct answers.

I managed to get the solution, I don't know where to post it so I make it below

        <?php
        include("db.php");
        if (isset($_POST['submit'])){

            $status = $_POST['status'];
            $area = $_POST['area'];
            $address = $_POST['address'];

            $input = $_POST;

            $table_name = 'tbl_name';

            $column = '*';

            $query = "SELECT $column FROM `$table_name`";

            $where = null;

            if (!empty($input['address'])) 
            {
               $where = "WHERE";
               $query .= " $where address LIKE '%".$input['address']."%'";
            }

            if (!empty($input['status']))
            {
            if (is_null($where))
            {
            $where = "WHERE";
            }
            else {
            $where = "AND";
            }
            $query .= " $where status='{$input['status']}'";
            }

           if (!empty($input['area']))
            {
           if (is_null($where))
            {
            $where = "WHERE";
            }
            else {
            $where = "AND";
            }
            $query .= " $where area='{$input['area']}'";
            }       

            $data = mysqli_query($conn, $query) or die('error');
            if(mysqli_num_rows($data) > 0){
                    while($row = mysqli_fetch_assoc($data)){
                        $contact_person = $row['contact_person'];
                        $status = $row['status'];
                        $area = $row['area'];
                        $address = $row['address'];
                    ?>
player
  • 21
  • 4

1 Answers1

0
WHERE ($address is null OR address LIKE '%".$address."%')
  AND ($status is null OR status LIKE '%".$status."%')
  AND ($area is null OR area = '$area')
juergen d
  • 201,996
  • 37
  • 293
  • 362