0

I'm displaying Spotlight post on search page.

When a user enters a keyword to search for a post I like to bring a Spotlight post using that keyword. If there is no post with that keyword then I would want to just bring any Spotlight post from database.

My questions is, can I check this in a MySQL query to see if they will be any results with this keyword, if not then ignore this keyword?

My query

SELECT id, title, desc 
  FROM post 
 WHERE isActive = 1 
   AND title = 'keyword'

but if I'm getting 0 results with this query I would like to ignore this and run this instead

SELECT id, title, desc 
  FROM post 
 WHERE isActive = 1
Lalajee
  • 139
  • 1
  • 9
  • Passing `$keywords` straight into the SQL - I hope you're escaped it using the proper MySQL API? – Romain May 07 '12 at 14:58

2 Answers2

0

desc is MySQL's reserved keyword (used for ordering results in a *desc*ending order). To use it as a column name, you need to put it in backticks

$select = " SELECT id, title, `desc` ";
$from = ' FROM post';
$where = 'WHERE isActive=1 and title="%$keywords%"';
$sql = $select.$from.$where;
Mchl
  • 61,444
  • 9
  • 118
  • 120
  • this is just a example. i didn't called the column desc – Lalajee May 07 '12 at 15:02
  • Ah... please make sure your example code is syntactically correct, because otherwise people trying to answer you will get confused... like me :) – Mchl May 07 '12 at 15:05
  • Also I believe you want `$where = "WHERE isActive=1 and title LIKE '%$keywords%'";` not `$where = 'WHERE isActive=1 and title="%$keywords%"';` but is that an example or actual code? – Mchl May 07 '12 at 15:07
  • What I have done is check for result if none found then try another query without any keywords. it works greate thank you for your help. – Lalajee May 23 '12 at 09:42
0

This is what I have done to solve my problem.

$select = " SELECT id, title, desc ";
$from = ' FROM post';
$where = 'WHERE isActive=1 and title="%$keywords%"';
$sql = $select.$from.$where;

if no result then overwrite

$where = 'WHERE isActive=1';
$sql = $select.$from.$where;

If anyone know anyother way please let me know.

Lalajee
  • 139
  • 1
  • 9