0

I am attempting a search between two values with an or condition but can not seem to get this to work. Here is my search:

$search = mysql_query("SELECT * FROM `data` WHERE (`Required ACT` between ($act1) and ($act2) OR (`Required SAT` between ($sat1) and ($sat2))");

It works fine when alone but when the "or" is intorduced it break.

Thanks!

Tom Canfarotta
  • 743
  • 1
  • 5
  • 14
  • Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Dec 28 '15 at 17:06
  • 2
    You don't have proper parentheses matches to get the OR condition to work. – Jay Blanchard Dec 28 '15 at 17:07
  • [Your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Jay Blanchard Dec 28 '15 at 17:07
  • 1
    You need to get in the habit of [accepting answers](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) that help you to solve your issues. – Jay Blanchard Dec 29 '15 at 01:31
  • Okay - great. How do I go about doing that? – Tom Canfarotta Dec 29 '15 at 05:02
  • There is a check mark next to each answer. Select the check mark next to the answer which has helped you on this and earlier questions. – Jay Blanchard Dec 29 '15 at 12:09

1 Answers1

2

By breaking the query over multiple lines and applying the logic you're looking for you'll see where your parentheses groups need to be:

SELECT * 
FROM `data` 
WHERE 
   (`Required ACT` BETWEEN ($act1) AND ($act2))
OR 
   (`Required SAT` BETWEEN ($sat1) AND ($sat2))
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
  • 2
    A surprising number of people are completely unaware of the fact that you can actually break queries onto multiple lines. – Niet the Dark Absol Dec 28 '15 at 17:16
  • If one more clause adding than I think it will not work – devpro Dec 28 '15 at 17:34
  • I think those parentheses are useless around variables. `.. BETWEEN $act1 AND $act2 ..` will be fine. – Shafizadeh Dec 28 '15 at 17:49
  • Thanks for the help this worked! Can you help me with one more item? Sicne this is an or statement there will be times when the $sat or $act variables are empty. Right now when queried with an empty variable it breaks. How would you deal with it when one or the other is empty? – Tom Canfarotta Dec 28 '15 at 20:35
  • You test the variables *before* you run the query @TomCanfarotta – Jay Blanchard Dec 28 '15 at 21:01