0

fI have what seems to be a relatively simple AND/OR clause that is giving me a bit of a headache.

$query = "SELECT stv.name,stc.tmplvarid,stc.contentid,stv.type,stv.display,stv.display_params,stc.value";
$query .= " FROM ".$tb1." stc LEFT JOIN ".$tb2." stv ON stv.id=stc.tmplvarid ";
$query .= " LEFT JOIN $tb_content tb_content ON stc.contentid=tb_content.id ";
$query .= " WHERE stv.name='".$region."' AND stc.contentid IN (".implode($cIDs,",").") ";
$query .= " OR stv.name='".$countries."' AND stc.contentid IN (".implode($cIDs,",").") ";
$query .= " AND tb_content.pub_date >= '$pub_date' ";
$query .= " AND tb_content.published = 1 ";
$query .= " ORDER BY stc.contentid ASC;";

I need it to retrieve the values from both $region and $countries. However, the way it is it only returns the value of $countries. If I remove the line with the OR it returns the value of $region, but it won't return both. What am I doing incorrectly?

MrSmith42
  • 9,961
  • 6
  • 38
  • 49
Vecta
  • 2,312
  • 5
  • 28
  • 47

2 Answers2

2

Try putting brackets around the clauses on either side of the OR. See below:

$query = "SELECT stv.name,stc.tmplvarid,stc.contentid,stv.type,stv.display,stv.display_params,stc.value"; 
$query .= " FROM ".$tb1." stc LEFT JOIN ".$tb2." stv ON stv.id=stc.tmplvarid "; 
$query .= " LEFT JOIN $tb_content tb_content ON stc.contentid=tb_content.id "; 
$query .= " WHERE (stv.name='".$region."' AND stc.contentid IN (".implode($cIDs,",").")) "; 
$query .= " OR (stv.name='".$countries."' AND stc.contentid IN (".implode($cIDs,",").")) "; 
$query .= " AND tb_content.pub_date >= '$pub_date' "; 
$query .= " AND tb_content.published = 1 "; 
$query .= " ORDER BY stc.contentid ASC;"; 
D'Arcy Rittich
  • 167,292
  • 40
  • 290
  • 283
  • Thanks, but it's still only returning $countries. Here's the function in it's entirety if that's helpful: http://pastebin.com/E4CdnQNj – Vecta Nov 09 '10 at 15:51
0

Looks like you are missing parentheses, no?

A or B and C or D is ambiguous, you need to use parentheses to make it clear you mean (A or B) and (C or D)

Gabriel Magana
  • 4,338
  • 24
  • 23