Question

so I have a blog system, and i want to build a section for "related news", I am not making a 'Tags' system but just simply searching and storing the current title of the article (which is pulled from the database) in a string and exploding it to be able to later put all the words into a query, that later query will search all titles in the database to find any of those words, and if it does, it will return the title in a list. Here is the relevant code:

// note to stackoverflow peeps, $row_object_title is just the title that is pulled form the database
$row_object_title_lower = strtolower($row_object_title);
$keywords = explode(" ",$row_object_title_lower);

Code that is run later on the page:

$keywords_imploded = implode("','",$keywords);
$myquery = sql_query("SELECT object_title FROM table WHERE object_title IN ('$keywords_imploded')

Now i try to list the titles by printing the title out, but nothing is display.

I am sure there is matching titles in the database.

Thanks

Was it helpful?

Solution 2

It seems as though you have misunderstood how the IN clause works.

The IN clause will look for what is on the left in the list of values on the right. For example: WHERE id IN (2,3,5) - if id is in that list it will return true. In your case it is the opposite.

Something like this should work for what your after but there are likely to be better alternatives.

$sql = '';
foreach ($keywords AS $keyword)
{
    if ($sql != '')
        $sql .= ' OR ';

    $sql .= "object_title LIKE '%$keyword%'";
}

$query = 'SELECT object_title FROM table WHERE '.$sql;

% is a wildcard.

Just please remember to escape the values first.

OTHER TIPS

Your array of keywords is generated with:

$keywords = explode(" ",$row_object_title_lower);

What if you have a title like "My Super Blog Post"? You're going to get:

$keywords = array( "My", "Super", "Blog", "Post" );

Later on, you query using those values imploded together:

$keywords_imploded = implode("','",$keywords);
$myquery = sql_query("SELECT object_title FROM table WHERE object_title IN ('$keywords_imploded')

The SELECT query is going to look like this:

SELECT object_title FROM table WHERE object_title IN ( 'My', 'Super', 'Blog', 'Post' );

I don't think that's going to find anything.

You need to re-evaluate how you're handling the list of titles (I think that's what you're going for, right?).

Try:

$keywords_imploded = join("','", $keywords);
$myquery = sql_query("SELECT object_title FROM table WHERE object_title IN ($keywords_imploded)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top