php - 值不等于折扣代码的文本框条目
问题描述
我正在尝试使用一个可以正常工作的简单折扣代码,但我想在输入错误代码时显示错误消息。到目前为止,我已经解决了这个问题,但消息一直显示,而不是仅在输入错误代码时显示。
$discount = ( int )$_GET[ 'discount' ];;
$codes = array(10, 20);
if ($discount == "10"){
$discount_total = round($grand_total * ((100-10) / 100), 2);;
$message = "Discount Code '" . $discount . "' has been successfully applied.";
}elseif (!in_array(intval($discount), $codes, true)){
$message = "Sorry, this code is not valid.";
$discount_total = $grand_total;
}else {
$discount_total = $grand_total;
}
解决方案
一开始,您已经将$discount
变量转换为int
类型:
$discount = ( int )$_GET[ 'discount' ];
只要相信你的代码。
$codes = array(10, 20);
// if ($discount == "10") { <--- this is bad, you compare your int value with string "10"
if ($discount === 10) { // <-- this is clear code
$discount_total = round($grand_total * ((100-10) / 100), 2);;
$message = "Discount Code '" . $discount . "' has been successfully applied.";
// } elseif (!in_array(intval($discount), $codes, true)){ <-- same mistake here, we dont need to cast $discount again
} elseif (!in_array($discount, $codes)) { // <-- this should just work fine, the only question: if you already checked value 10, why not just to check 20? why do you check against array of 2 values?
$message = "Sorry, this code is not valid.";
$discount_total = $grand_total;
} else {
$discount_total = $grand_total;
}
更新如果您想检查是否发送了 GET 参数,您可以使用以下命令包装所有这些片段:
if (isset($_GET['discount'])) {
...
}
推荐阅读
- firebase - 如何解决错误路径中不能包含 //。Firestore 颤动错误
- python - ModuleNotFoundError 与 Spyder
- java - 将文件用于共享内存 IPC
- java - 默认标头 OpenAPI 3.0 | Java Jaxrs-RestEasy
- javascript - 由工作流创建后重定向到新创建的 Dynamics 365 记录
- apache-zookeeper - Zookeeper zookeeper.forceSync、Zab 和 Paxos
- c# - 如何让 winappdriver 找到应用程序文件?
- javascript - 无法让我的主进程和渲染器进程在电子中进行通信
- javascript - 如何将多个对象添加到一个 JSON 文件中,然后列出该文件中的所有内容?[JSON、JavaScript]
- firebase - Flutter web firebase/firestore错误运行