0

How to select results from table where cat = '$cat' and if it's not equal then select all from cat no matter what $cat is. Here is my query

$sql = mysql_query("SELECT * FROM `obiavi` WHERE `postdate`+`days`*86400 > $time AND `town` IN ('$oblasti') AND `desc` LIKE '%$keyword%' ORDER BY id DESC LIMIT $start, $perpage") or die (mysql_error());
k1tkat
  • 57
  • 1
  • 7
  • i don't get the problem correctly... maybe this is your solution? `where (cat = $cat or cat != $cat)` – Michael Walter Jul 17 '13 at 14:38
  • Do you mean if `cat = $cat` returns 0 results? – George Reith Jul 17 '13 at 14:41
  • Can you rephrase your question? It doesn't have a lot of sense for me. "if it's not equal" > If what is not equal to what? – Racso Jul 17 '13 at 14:41
  • This is not possible with a single query. `WHERE` is applied at row selection time, e.g. as each row in the table is scanned by the DB. You need knowledge of the future to handle the case of detecting that no `cat` values match at all, but that knowledge isn't available until AFTER the entire table is scanned. – Marc B Jul 17 '13 at 14:43
  • Do you mean this: select rows where `cat = '$cat'`, but if that returns nothing then select all rows? – Ed Gibbs Jul 17 '13 at 14:45
  • Please **DO NOT** use `mysql_query` in new code, and **always** [properly escape](http://bobby-tables.com/php) your values. Without escaping, this one line of code could destroy your entire application. – tadman Jul 17 '13 at 14:48
  • I'm wrong, everyone is right, it returns everything. lol... – The Alpha Jul 17 '13 at 14:56

1 Answers1

1

From my understanding, you want only results where cat = '$cat'. If you obtain no results, then you want to have results no matter what their cat is.

This cannot be done effectively in a single query, you need to use two queries.

If your first query with the condition returns no results, then you attempt the second query, without the cat condition.

Best practices

Consider defending yourself against MySQL Injections

Also, please consider using MySQLi or PDO instead of MySQL.

Community
  • 1
  • 1
Dany Caissy
  • 3,176
  • 15
  • 21