在MySQL中输出错误

时间:2016-03-28 16:04:09

标签: php mysql

我正在编写一个Android应用程序,我必须从MySQL中检索数据。但我的输出结果不对。

表名是血,结构如下

structure of the table

php代码如下

<?php
   $con=mysqli_connect("server","username","password","databasename");

$city = "HYDERABAD";
$blood = "APOSITIVE";

$sql = "select name,blood,age,lastdonated,mobile,email,state,city,sex from blood where upper(blood) = '$blood' OR lower(blood) = '$blood' AND upper(city) = '$city' ORDER BY id DESC LIMIT 1000 ";

$res = mysqli_query($con,$sql);

$result = array();

while($row = mysqli_fetch_array($res)){
array_push($result,
array('name'=>$row[0],
'blood'=>$row[1],
'age'=>$row[2],
'donated'=>$row[3],
'number'=>$row[4],
'email'=>$row[5],
'state'=>$row[6],
'city'=>$row[7]
));
}

echo json_encode(array("feedAnegative"=>$result));

mysqli_close($con);

?>

输出

{
   "feedAnegative":[
      {
         "name":"saicharan",
         "blood":"APOSITIVE",
         "age":"19",
         "donated":"0000-00-00",
         "number":"8794511258",
         "email":"dsaicharan219@gmail.com",
         "state":"andhrapradesh",
         "city":"vijayawada"
      },
      {
         "name":"b",
         "blood":"Apositive",
         "age":"20",
         "donated":"0000-00-00",
         "number":"1234567892",
         "email":"b@gmail.com",
         "state":"Telangana",
         "city":"khammam"
      },
      {
         "name":"a",
         "blood":"APOSITIVE",
         "age":"20",
         "donated":"0000-00-00",
         "number":"1245863921",
         "email":"a@gmail.com",
         "state":"telangana",
         "city":"hyderabad"
      }
   ]
}

在上面的json feed中我应该得到与city = hyderabad相关的数据。 但我得到了表中血液是APOSITIVE的所有记录。错误在哪里?

1 个答案:

答案 0 :(得分:1)

决定结果集中行的因素是发送给MySQL的SQL查询,而不是PHP代码:

select name,blood,age,lastdonated,mobile,email,state,city,sex
from blood
where upper(blood) = 'APOSITIVE' OR lower(blood) = 'APOSITIVE' AND upper(city) = 'HYDERABAD'
ORDER BY id DESC
LIMIT 1000

如果您不使用括号来设置运营商优先级,default ones适用:

  

运算符优先级显示在以下列表中,从最高优先级到最低。一起显示的运算符   一行具有相同的优先权。

INTERVAL
BINARY, COLLATE
!
- (unary minus), ~ (unary bit inversion)
^
*, /, DIV, %, MOD
-, +
<<, >>
&
|
= (comparison), <=>, >=, >, <=, <, <>, !=, IS, LIKE, REGEXP, IN
BETWEEN, CASE, WHEN, THEN, ELSE
NOT
AND, &&
XOR
OR, ||
= (assignment), :=

所以你的WHERE子句相当于:

where upper(blood) = 'APOSITIVE' OR
    (lower(blood) = 'APOSITIVE' AND upper(city) = 'HYDERABAD')

此外,blood列具有latin1_general_ci归类,因此lower(blood) = 'APOSITIVE'实际上可以匹配(不知道为什么会这样开始)。