Page 1 of 1

Database Searching

Posted: Sat Feb 25, 2012 2:33 am
by liquiddrive
Hello,

I've just been following the "Database Searching" tutorial (http://betterphp.co.uk/playlist.html?pi ... 759BABE5EC) but unfortunately, every search seems to return an empty array.

Here is the code for my 'search.inc.php' in the tutorial this was the function file (blog_posts.inc.php)
function search_tags($term) {
	$tags = preg_split('#\s+#', mysql_real_escape_string($term));
	
	$sql = "SELECT * FROM wallpapers WHERE image_tags='$tags'";
	
	$result = mysql_query($sql);
	$results = array();
	
	while (($row = mysql_fetch_assoc($result)) !== false){
		$results[] = $row;
	}
	
	return $results;
}
In my table 'wallpapers' I have a column for the images named, 'image_tags'. Inside of that column, the tags are displayed like so:
city,tokyo,night
I manually removed the spaces whilst I work on this project, I will eventually remove the spaces when the image is uploaded/submitted. But the tags will be separated by a comma for each image.

Sorry for rambling on. Back to to my error, here is my 'search.php' file
// My init.inc.php file is included above all of this

if (empty($_GET['term']) === false) {
	$search_results = search_tags($_GET['term']);
				
	if (empty($search_results)) {
		echo 'Your search returned no results.'; 
	}
				
	foreach ($search_results as $search_result) {
		echo '<img src="'.$search_result['thumb_path']."';
	}
}
When for example, you search for either of the tags shown in the above quote (city, tokyo or night) the image isn't displayed.

Any ideas where I could possibly be going wrong?

Re: Database Searching

Posted: Sat Feb 25, 2012 9:46 pm
by jacek
You can't just use the result of preg_split in the sql like that. you have to turn it into an sql IN() statement which is what I did in the video ?

Re: Database Searching

Posted: Sat Feb 25, 2012 10:16 pm
by liquiddrive
Just had a quick look at the video, I can't see an IN() statement used?

Re: Database Searching

Posted: Mon Feb 27, 2012 11:53 am
by jacek
liquiddrive wrote:Just had a quick look at the video, I can't see an IN() statement used?
Your right, sorry. We cant use IN because we only want to match part of the string...

You should have two lines that look like this though
	$title_where	= "`post_title` LIKE '%" . implode("%' OR `post_title` LIKE '%", $keywords) . "%'";
	$body_where		= "`post_body` LIKE '%" . implode("%' OR `post_body` LIKE '%", $keywords) . "%'";