Advanced search PHP / MYSQL script. How?

I need some guidance to do an advanced search script for the website I'm working on.

I already know how to search the database for simple queries. The problem I'm facing right now is the search when using multiple select boxes. For instance:

enter image description here

This is a simple form with various search options. The question arises:

The visitor can choose to search by country or city, both or even with all three options.

How can I catch this in a PHP script? Do I have to check if a city has been selected, and based on this, a query is launched? But if I do, I will have to make different requests based on each choice.

In pseudo code, it will be something like this: (I suppose)

- , .

, ? ?

?

.

+5
3

, , AND.

$conditions = array();
if ($formCondition1) {
  $conditions[] = 'state = "'.$somevalue.'"';
}
if ($formCondition2) {
  $conditions[] = 'country = "'.$somevalue.'"';
}
...
if ($formConditionN) {
  $conditions[] = 'N = "'.$somevalue.'"';
}

// , - ANDs ( ORs, , , )

$sqlStatement = 'SELECT field1, field2 FROM tableABC WHERE '.implode(' AND ', $conditions);

: , , , 1 . EDIT: lol jswolf, :)

+6

$where, , implode "" . - :

$where = array();
if $city is defined
    $where[] = "city = '".mysql_real_escape_string($city)."'";
fi
if $country is defined
    $where[] = "country = '".mysql_real_escape_string($country)."'";
fi
...

if(count($where)) {
    $query.= ' WHERE '.implode(' AND ', $where);
}
+5

I would try something like:

$qry = "SELECT * FROM table WHERE ";
if ($country != '') {
    $qry .= "country='".mysql_real_escape_string($country)."' AND "
}
if ($city != '') {
    $qry .= "city='".mysql_real_escape_string($city)."' AND "
}
$qry .= '1';
$res = mysql_query($qry);

The request is created depending on what is installed. Note the “1” at the end of the query string, which is always true. This is necessary in order to follow "WHERE" if $ country and $ city are empty or follow the last "AND" if it is not.

+4
source

All Articles