我正在尝试使用REST API服务,并检查某些表中是否存在该参数。
场景:
我的问题:
如果我只使用 if-else ,它可以工作,但是如果我包含 else if ,它会返回 null
我在做什么错了?
代码:
<?php
header("Content-Type:application/json");
//if (isset($_GET['licence']) && $_GET['licence']!="") {
$licence = $_GET['licence'];
$query = mysqli_query($con,"SELECT id, licence,
period, users FROM licence WHERE licence='$licence'");
$counts = mysqli_num_rows($query);
if ($counts>0) {
// get retrieved row
while($row = mysqli_fetch_array($query)){
// create array
$user_arr=array(
"status" => true,
"message" => "Successfully Validated!",
"id" => $row['id'],
"licence" => $row['licence'],
"period" => $row['period'],
"user" => $row['users'],
"mstatus" => $row['status']
);
}
} elseif ($counts==0) {
$querys = mysqli_query($con,"SELECT
COUNT(licence) num,
licence, period, users FROM licence_used
WHERE licence='$licence'");
$row = mysqli_fetch_array($querys);
$count = mysqli_num_rows($querys);
if ($count > 0) {
if ($row['num'] == $row['users']) {
$user_arr=array(
"status" => false,
"message" => "Licence key entered has been used by ".$row['users']." users. Please purchase another licence.",
);
} else {
while($row = mysqli_fetch_array($querys)){
// create array
$user_arr=array(
"status" => true,
"message" => "Successfully Validated!",
"id" => $row['id'],
"licence" => $row['licence'],
"period" => $row['period'],
"user" => $row['users'],
"mstatus" => $row['status']
);
}
}
}
} else {
$user_arr=array(
"status" => false,
"message" => "Invalid Licence Key Entered. Please contact the software company.",
);
}
// make it json format
print_r(json_encode($user_arr));
//}
?>
答案 0 :(得分:0)
优良作法是避免嵌套太多ifs / elses,这会使代码更难阅读和调试。
最后一个是无法到达的,并且总结果将不会是<0
您还可以将用例拆分为函数,然后进行相应调用,这是使代码可读的另一种好方法。
作为示例,我对您的代码做了一些更改,此处的代码看起来很糟糕,所以我改用pastebin。
(我必须包含一些代码,因为stackoverflow要求使用粘贴框,但是如果需要,可以忽略它,这是打印结果的推荐功能)。
<?php
header("Content-Type:application/json");
function reply($reply){
print json_encode($reply);
exit;
}
希望对您有帮助。