Jump to content

Search MySQL field for values in an array


amavadia

Recommended Posts

Hopefully this will be an easy one for someone...

 

I have...

 

array called $loc

a MySQL table called advert

a Field within the table called location

 

Im trying to...

Search for records which contain any of the values in the array in the location field.

 

So far ive got a query which will find a record if there is just one value in the field. But if the field contains more than 1 value, it dosen't find the record even if that field contains one of the values in the search array. Values in the Location field are storred separated by commas, so my guess is I need to add something to the search query to account for the spaces and and commas?

 

$query = "SELECT * 
FROM advert 
WHERE location IN('".join("','", $loc)."')";

 

any help appreciated!

Link to comment
Share on other sites

I use a function like this:

 

function parsesearch($search) {
	$searches = split(" ", $search);
	$searchqty = count($searches);
	for($x=0;$x<$searchqty;$x++) {
		if(!isset($searchquery)) $searchquery = " WHERE (title_keys.title LIKE '%".$searches[$x]."%' OR ips.domain LIKE '%".$searches[$x]."%')";
		else $searchquery .= " AND (title_keys.title LIKE '%".$searches[$x]."%' OR ips.domain LIKE '%".$searches[$x]."%')";
	}
	return $searchquery;
}

 

You may need to tailor it to your needs but hopefully it gives you a starting point.

Link to comment
Share on other sites

I use a function like this:

 

function parsesearch($search) {
	$searches = split(" ", $search);
	$searchqty = count($searches);
	for($x=0;$x<$searchqty;$x++) {
		if(!isset($searchquery)) $searchquery = " WHERE (title_keys.title LIKE '%".$searches[$x]."%' OR ips.domain LIKE '%".$searches[$x]."%')";
		else $searchquery .= " AND (title_keys.title LIKE '%".$searches[$x]."%' OR ips.domain LIKE '%".$searches[$x]."%')";
	}
	return $searchquery;
}

 

You may need to tailor it to your needs but hopefully it gives you a starting point.

 

Thanks for that but I think ive found an easier way of making up the search query string:

 

$query = "SELECT * 
FROM advert 
WHERE location LIKE '%" .
join("%' OR location LIKE '%", $loc) . "%'";

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.