Page 1 of 1

Re: multiple words search form

Posted: Sat Oct 11, 2014 8:13 am
by Celauran

Code: Select all

$query = "SELECT * FROM privatelistings WHERE make LIKE '%$searchTerm%'";
You're passing in a single search term while your description suggests you may want multiple. What if you split apart the query string on spaces to break out the individual words, then iterated over the results to construct your WHERE clause?

Re: multiple words search form

Posted: Sat Oct 11, 2014 8:42 am
by Celauran

Re: multiple words search form

Posted: Sat Oct 11, 2014 9:04 am
by Celauran
There may be a % missing from model, but it otherwise looks fine. What about the multiple word search you were referring to in the first post?

Re: multiple words search form

Posted: Sat Oct 11, 2014 9:11 am
by Celauran
A few things here. Since you're adding % before and after a search term, what's going to happen if that search term is empty? After running trim on an input, if that input is an empty string, you probably want to exclude it from the search altogether. That will address the test problem.

Re: multiple words search form

Posted: Sat Oct 11, 2014 9:25 am
by Celauran
That's better than returning everything, but what if I'm just interested in a make and not necessarily a specific model (ie. what if I want all results for Acura)?

Re: multiple words search form

Posted: Sat Oct 11, 2014 9:36 am
by Celauran
What about using something like

Code: Select all

$make  = trim($_GET['make']);
$model = trim($_GET['model']);

$where = [];
if (!empty($make)) {
	$where[] = "make LIKE '%{$make}%'";
}
if (!empty($model)) {
	$where[] = "model LIKE '%{$model}%'";
}

$where_clause = implode(' OR ', $where);

if (!empty($where_clause)) {
	$query = "SELECT * FROM privatelistings WHERE {$where_clause}";
}
Note there are definitely problems with this, like the lack of input sanitization and the use of SELECT *, but it should give you the right idea.

Re: multiple words search form

Posted: Sat Oct 11, 2014 10:02 am
by Celauran
If you're using a really old version of PHP, replace [] with array()

Re: multiple words search form

Posted: Sat Oct 11, 2014 10:52 am
by Celauran
ianhaney wrote:

Code: Select all

//check whether the name parsed is empty
if($make == "" || $model = "")
{
	echo "Enter the make and model you are searching for.";
	exit();
}
Should this even be in your code? The query is deliberately flexible, but this snippet above still requires both fields be filled.