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 对于这个复杂问题的解释说明
  • ¥50 三种调度算法报错 采用的你的方案
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败