使用“ OR”进行MySql PHP查询时,如何知道两个条件中的哪一个得到满足?
示例:
if($mysql->query("SELECT * FROM `table` WHERE cpf = '0' OR state = '0'")->fetch_assoc()){
//Which was satisfied?
}
请记住,在每个查询中,最多会有2条记录。
我考虑过这样做:
if($th = $mysql->query("SELECT * FROM `table` WHERE cpf = '0' OR state = '0'")->fetch_assoc()){
while($row = $th){
if($row['cpf'] == "0"){
echo "CPF";
}else if($row['state'] == "0"){
echo "state";
}
}
}
但是,没有做到这一点的“正确”方法吗?不需要这些ifs吗?
答案 0 :(得分:1)
必须检查从执行查询得到的结果数组中获得的信息。
if($row = $mysql->query("SELECT * FROM `table` WHERE cpf = '0' OR state = '0'")->fetch_assoc()){
if ($row['cpf'] == 0) { /* cpf satisfied*/ }
if ($row['state'] == 0) { /* state satisfied*/ }
}
一个小建议:尝试使用$mysqli
而不是$mysql
您还可以检查以下内容:
SELECT *,
(CASE WHEN cpf = '0' THEN 'cpf satisfied'
WHEN state = '0' THEN 'state satisfied' END) AS satisfied
FROM `table` WHERE cpf = '0' OR state = '0'
答案 1 :(得分:0)
您不能真正知道两个条件中的哪个已被满足。如果您想知道,则必须像下面这样分别执行它们:
if($mysql->query("SELECT * FROM `table` WHERE cpf = '0'")->fetch_assoc()){
//cpf = 0 was satisfied
}
if($mysql->query("SELECT * FROM `table` WHERE state = '0'")->fetch_assoc()){
//state = 0 was satisfied
}