Today when I was coding for one of my projects, I required to use OR and AND queries together. And with having good experience in Mysql and PHP Programming, I thought I can do it easily. But when I did use the query, It was not working as expected. After analyzing my query, I got to know that it was checking AND and OR conditions separately and giving result even when AND condition is false because I forgot to use Bracket with OR conditions.
My Requirement: Select employee_id of all employers with common name 'John' , age>24 or city London
Name should be John
Age or City condition (One of them should be true)
Problematic Query:
$sql = "Select employee_id from employers where employers.employee_name = '$name' AND employee_age > '$age' OR employee_city = '$city'";
It gives me result set with names other than John
Solution Query:
$sql = "Select employee_id from employers where employers.employee_name = '$name' AND (employee_age > '$age' OR employee_city = '$city')";
Updating all values using Single Query
Table which needs modification: TableA
Column whose value we need to change: ColA
Present Value: 2
New Value : 3
Query will be
My Requirement: Select employee_id of all employers with common name 'John' , age>24 or city London
Name should be John
Age or City condition (One of them should be true)
Problematic Query:
$sql = "Select employee_id from employers where employers.employee_name = '$name' AND employee_age > '$age' OR employee_city = '$city'";
It gives me result set with names other than John
Solution Query:
$sql = "Select employee_id from employers where employers.employee_name = '$name' AND (employee_age > '$age' OR employee_city = '$city')";
Updating all values using Single Query
Table which needs modification: TableA
Column whose value we need to change: ColA
Present Value: 2
New Value : 3
Query will be
UPDATE TableA
SET ColA = '3'
WHERE ColA = '2'
No comments:
Post a Comment