Matei Panchios
Matei Panchios

Reputation: 3

Search not working as intended

Why won't my search function ever execute the "else" (else should echo a text when no resulsts haved been found)? I also have some problems when trying to show all results (with no search criterias selected, just by pressing the search button). I'll upload the whole code of the page because I don't know if you need the HTML part as well or not to figure out the problem. I know it's a big chunk of code but please help out if you can. Thanks!

Here's a link to my code: http://pastebin.com/BXe1C0dr

Upvotes: 0

Views: 60

Answers (1)

invisal
invisal

Reputation: 11181

This is not yet the answer, just a brief code structure of Matei Panchios code. Because it is hard to make sense of long code, so I try to simplify it so that other people might be able to help.

$termeni = mysql_real_escape_string($_POST['termeni']);
$tip=$_POST['tip'];
$judet=$_POST['judet'];

if((!empty($termeni)) and (isset($tip))  and (isset($judet))) {
     $query = "SELECT * FROM oferte WHERE localitate LIKE '%$termeni%' AND 
              tip_locatie='$tip' AND judet='$judet'";
     // do the query and write some HTML
} elseif (isset($tip)) {
     $query = "SELECT * FROM oferte WHERE tip_locatie='$tip'";
     // do the query and write some HTML
} elseif (isset($judet)) {
     $query = "SELECT * FROM oferte WHERE judet='$judet'";
     // do the query and write some HTML
} elseif (!empty($termeni)) {
    ...
} elseif (!empty($termeni) AND (isset($judet))) {
    ...
} elseif (!empty($termeni) AND (isset($tip))) { 
    ...
} elseif ((isset($judet)) AND (isset($tip))) {
    ...
} elseif ((!isset($judet)) AND (!isset($tip)) AND (empty($termeni))) {
    ...
}  else {
    // I believe this where it does not get executed.
}

Well, it makes sense why it does not get executed because there is other way that the elseif does not cover. If you look from this point of view

  • If three variable is set
if((!empty($termeni)) and (isset($tip))  and (isset($judet))) {
  • If two variables is set
elseif (!empty($termeni) AND (isset($judet)))
elseif (!empty($termeni) AND (isset($tip)))
elseif (!empty($termeni) AND (isset($tip)))
elseif (!empty($termeni) AND (isset($tip)))
  • If one variable is set
elseif (isset($tip))
elseif (isset($judet))
elseif (!empty($termeni))
  • When no variable is set
elseif ((!isset($judet)) AND (!isset($tip)) AND (empty($termeni)))
  • which leave else condition with nothing to cover.

If I were you, I would structure the code as following.

if (!empty($termeni) and isset($tip)  and isset($judet)) {
    query = '....';
} elseif (!empty($termeni) and isset($judet) {
    query = '....';
} // .... the rest of the condition

$result =  mysql_query($query);
if (mysql_num_rows($result) > 0) {
   // write HTML table
} else {
   // write message that there is no result found
}

This will reduce the size of your code by 6 times.

Upvotes: 2

Related Questions