1

I need to know how to query a mysql database based on multiple and conditions... im trying to find all male users online above age 18.

php code :

$sql = mysql_query("Select * FROM `users` where `round`= '".$userData["round"]."',
    `sex` = 'm', `age` = '18', `online_stas` = 'online'
    ")or die(mysql_error());
  • 1
    I think you have a bigger problem here. Storing age in a table is almost always a bad idea. Next year all the data in your table will be incorrect as everyone will be a year older. It is much better to store date of birth and calculate age on retrieval of the data. – user1191247 Mar 14 '12 at 19:21

4 Answers4

2

Reading responses and the fact that you still have errors, I come to think the posibility of having "M" instead of "m" in sex field.

You can try:

$sql = mysql_query("SELECT * FROM `users`
                   WHERE UPPER(`sex`) = 'M'
                   AND `age` > 18
                   AND `online_stas` = 'online'")
       or die(mysql_error());

I removed the round check based on your statement that you want all male users online being older than 18, but can be added again. Other posible fail can be the comparison of age with string value 18 instead of numeric value 18, so I changed that too (despite it may work and be converted automatically, but better to check with same types if something changes in a future).

Try it and tell if it worked.

StormByte
  • 1,266
  • 1
  • 13
  • 33
1

Try using AND.

$sql = mysql_query("Select * FROM `users` where `round`= '".$userData["round"]."' AND
    `sex` = 'm' AND `age` >= '18' AND `online_stas` = 'online'
    ")or die(mysql_error());

Also, I changed your age check to use >= instead of =, due to your description stating you want all users above age 18, not equal to. I'm also assuming you want to include those who are 18 as well as those above, if not, change it to >.

kitti
  • 14,663
  • 31
  • 49
  • 1
    @YoungnateDaGreat What error are you getting? I can't help you if I don't know what the error is. – kitti Mar 14 '12 at 18:53
0

You'll want to use WHERE and AND, ending up with the following conditions:

"... WHERE `round`= '".$userData["round"]."' AND `sex` = 'm' AND `age` > 18 AND `online_stas` = 'online'"
Wiseguy
  • 20,522
  • 8
  • 65
  • 81
rjz
  • 16,182
  • 3
  • 36
  • 35
0

You need to use AND when specifying multiple conditions.

$sql = mysql_query("SELECT * FROM `users` WHERE `round`= '". mysql_escape_string($userData["round"])."' AND `sex` = 'm' AND `age` = '18' AND `online_stas` = 'online'") or die(mysql_error());

Also, for security pruproses, you may want to escape queries parameters with mysql_escape_string().

Pierre-Olivier
  • 3,104
  • 19
  • 37