doushupu2521 2014-04-18 17:38
浏览 52
已采纳

如果一个字段不为空,那么所有字段都不为空

Is there an efficient way of processing part of a form that has three input fields. If all are empty then don't do anything, but if one is filled, all must be filled.

At the moment I have this

if (isset($_POST['desc1']) && !empty($_POST['desc1'])){
$email_message .= $_POST['desc1']. " - " . $_POST['code1']. " - Amount: " .$_POST['quant1']."<br>";
$toadd .= $_POST['desc1']. " - " . $_POST['code1']. " - Amount: " .$_POST['quant1']."<br><br>"; 
}

Problem is they could have entered the desc1 but not the code1 or quant1 and it will fire anyway. If they entered code1 or quant1 and not the desc1 nothing will happen, which again is a problem, I would like to display this as an error and have them go back and try again.

  • 写回答

2条回答 默认 最新

  • dstd2129 2014-04-18 17:55
    关注

    There are many ways to go about this.

    $required = array('desc1', 'code1', 'quant1');
    $errors = array();
    $fields_set = 0;
    
    foreach ($required as $rq) {
        if (isset($_POST[$rq])) {
            $fields_set++;
        } else {
            $errors[$rq] = "{$rq} is not set...";
        }
    }
    
    $valid = ($fields_set == 0 || $fields_set == count($required)) ? true : false;
    
    if ($valid) {
        // do stuff
    } else {
        print_r($errors);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图