Jump to content

Problem with search term


JohnOP

Recommended Posts

I am creating a search function for my friends system where users can search amongst there friends.

 

I have it working where it will search everyones friends with the search term and display what it finds but of course i only want it to get the user whom is searching friends.

 


function search_results($keywords){

$return_results = array();
$where = "";


$keywords = preg_split('/[\s]+/', $keywords);
$total_keywords = count($keywords);

foreach($keywords as $key=>$keyword){
	$where .= "`friend` LIKE '%$keyword%'";
	if ($key != ($total_keywords - 1)){
	$where .= " AND ";
	}
}

   
$results = "SELECT `friend`, `friend_gender`, `friend_location` FROM friends WHERE  $where";
$results_num = ($results = mysql_query($results)) ? mysql_num_rows($results) : 0;

if ($results_num === 0){
	return false;
}else{
while($results_row = mysql_fetch_assoc($results)){
$return_results[] = array(
		'friend' => $results_row['friend'],
		'friend_gender' => $results_row['friend_gender'],
		'friend_location' => $results_row['friend_location']
);
}
return $return_results;
}
}

 

When i edit it a bit to

$username = $_SESSION['username'];
$results = "SELECT `friend`, `friend_gender`, `friend_location` FROM friends WHERE username = '$username' AND  $where";

 

If just comes back with not finding anyone.

 

Anyone know if i am going wrong somewhere here?

Link to comment
https://forums.phpfreaks.com/topic/244150-problem-with-search-term/
Share on other sites

You are producing a query that looks like -

SELECT `friend`, `friend_gender`, `friend_location` FROM friends WHERE `friend` LIKE '%keyword1%' AND `friend` LIKE '%keyword2%'

 

That only matches rows when the where clause is TRUE. That would require that `friend` is like %keyword1%' and `friend` is like '%keyword2% at the same time, which will never be true (unless keyword1 is the same as keyword2). You actually need to use a logical OR. You want to match rows where `friend` is like %keyword1%' OR where `friend`is like '%keyword2%

I noticed that i don't even need to search for more than one keyword as the user can only search for usernames being one word, so i changed it to

 

"SELECT `friend`, `friend_gender`, `friend_location` FROM friends WHERE username = '$username' AND friend LIKE '%$keywords%'";

 

Works now.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.