Database Searching

Post here is you are having problems with any of the tutorials.
Post Reply
liquiddrive
Posts: 10
Joined: Fri Nov 04, 2011 9:52 pm
Contact:

Database Searching

Post 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?
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: Database Searching

Post 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 ?
Image
liquiddrive
Posts: 10
Joined: Fri Nov 04, 2011 9:52 pm
Contact:

Re: Database Searching

Post by liquiddrive »

Just had a quick look at the video, I can't see an IN() statement used?
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: Database Searching

Post 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) . "%'";
Image
Post Reply