Reputation: 413
I am having a wierd issue on a query, I am simply doing a search using 2 dates, I have all the dates in the database formatted in 2012-12-02 00:00:00 mysql format, but it is simply ignoring the AND cslblicstat = '10' AND wcxdate BETWEEN '$date1' AND '$date2' and giving me anything that has the matching class.
$user = $session->username;
if(isset($_POST['carrier'])){
$carrier = $_POST['carrier'];
$class[] = $_POST['class'][0];
$date1 = $_POST['date1'];
$date1 = date("Y-m-d 00:01", strtotime($date1));
$date2 = $_POST['date2'];
$date2 = date("Y-m-d 59:59", strtotime($date2));
foreach( $class as $key){
$query = "SELECT * FROM leads WHERE class1 = '$key' OR class2 = '$key' OR class3 = '$key' OR class4 = '$key' OR class5 = '$key' OR class6 = '$key' OR class7 = '$key' OR class8 = '$key' OR class9 = '$key' OR class10 = '$key' OR class11 = '$key' OR class12 = '$key' AND user = '' AND wccompcode = '$carrier' AND cslblicstat = '10' AND wcxdate BETWEEN '$date1' AND '$date2' LIMIT 100";
$sellead = mysql_query($query)or die(mysql_error());
while($leads = mysql_fetch_array($sellead)){
$arrayl[] = $leads;
$rowid = $leads['ID'];
$update = mysql_query("UPDATE leads SET user = '$user' WHERE ID = '$rowid'")or die(mysql_error());
}
}
}
Upvotes: 1
Views: 140
Reputation: 3200
In MySQL AND is evaluated before OR. So your WHERE clause is equivalent to this:
SELECT 1 OR 0 AND 0;
The result is true:
+--------------+
| 1 OR 0 AND 0 |
+--------------+
| 1 |
+--------------+
Also, a syntactically simpler method of expressing your OR conditions would be something like this:
WHERE '$key' IN ( class, class2, class3, ... ) AND ... ;
But anytime you have columns like that with numbers, what it really means is that your schema can be improved.
Upvotes: 1
Reputation: 115510
In SQL, AND
operator has higher precedence than OR
. I guess that you just need to put the ORed conditions into parentheses:
SELECT *
FROM leads
WHERE (class1 = '$key' OR class2 = '$key' OR ... OR class12 = '$key')
AND user = ''
AND wccompcode = '$carrier'
AND cslblicstat = '10'
AND wcxdate BETWEEN '$date1'
AND '$date2'
LIMIT 100
When in doubt about precedence of operators, use parenthesis (or consult the manual).
You could also write that condition with IN
:
WHERE '$key' IN (class1, class2, ... , class12)
AND user = ''
---
Upvotes: 3