Page 1 of 1

Matching a word in a field

Posted: Thu Jun 15, 2006 7:07 am
by Wardy7
I have a site I write news articles for that I want to be able to list certain stories that contain a certain word to be displayed on a page but I am unsure on how to do the search for this as currently I can only display things when I match a complete record which is too restrictive.

This is how I currently how I feth the news to one of the pages but it's not how I wnat to do it to other pages.
$query = "SELECT title,news,publisher,url,date,newsid FROM news WHERE newsid='$newsid' ORDER BY date";

An example of how I would like it would be so it displayed all news articles that matched 1 word in the "title" field for example if the title field contained the word "car".

I'm guessing this is pretty simple but having had a look on php.net I can't figure it :oops:

Cheers
Wardy

Posted: Thu Jun 15, 2006 7:26 am
by GM
you need to use LIKE in your SQL statement:

Code: Select all

SELECT * FROM NEWS WHERE TITLE LIKE '%$searchterm%'
The percentage signs are the SQL equivalent of the wildcard * and means "match any characters".

Posted: Fri Jun 16, 2006 9:02 am
by printf
If you want to match exact whole words then use a regex....

examples (sail, motor)

using LIKE...

Would match things like (sail, sailing, sailboat, motorboat, motors)

Using a regex

Would match only whole words (sail, motor)

Code: Select all

SELECT title FROM my_table WHERE title REGEXP '[[:<:]]sail|motor[[:>:]]';

pif