Searching for images by keyword

I’m working on a site that will provide stock images for sale. Probably the most important factor in the success of the site will be how efficient the search facility is. Each image will have maybe 40-50 keywords and visitors will need to search by keyword, with all matching files showing up quickly. Does this involve major programming, and if so wheres a good place to learn the basics. I’m not too hot on programming (hence my love of Freeway!), but if thats what it takes, I’m prepared to knuckle down and do it.


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options

If you’re wanting to search by keywords, the simplest way I can think of is to have a single text field in your database for keywords, and enter them either space- or comma-separated. Then search for the words using a “LIKE” query:

$sql = "SELECT * FROM images WHERE keywords LIKE '%" . $keyword . "%' ORDER BY filename ASC";

In other words, yes, this will take a bit of programming, but probably not all that much. What will take time is entering all of the keywords. What I would do is make an admin interface where you would see a preview of each image, and have a text field for entering or editing the keywords.

Now the query above will work fine for any single keyword entered. If you want to allow more complex queries, then you’ll need to break down what your visitor enters into an array of individual keywords. So if they enter ‘yellow flower’, you would want to make a query that found cases where both words were in the keywords:

$sql = "SELECT * FROM images WHERE keywords LIKE '%yellow%' AND keywords LIKE '%flower%' ORDER BY filename ASC";

To break out the multiple entries from the input text, I like to use a regular expression tool called preg_split:

$words = preg_split('/[s,]+/',$search_terms,-1,PREG_SPLIT_NO_EMPTY);

This will give you a simple array, like this:

Array(
    0 => 'yellow',
    1 = > 'flower'
)

And then you can generate the query programmatically inside a loop, like this:

foreach($words as $k=>$word){
    $words[$k] = 'keywords LIKE '%' . $word . '%'';
}
$where = implode(' AND ', $words);
$sql = "SELECT * FROM images WHERE " . $where . " ORDER BY filename ASC";

This seems tricky until you do it a few times, but it’s a worthwhile thing to learn.

Walter


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options