如果条件不允许留空字段

时间:2015-06-10 07:47:05

标签: php html forms if-statement conditional-statements

我有联系表单,您可以在其中添加多个收件人,但是当我将其上传到服务器上时,会出现以下错误:

  

注意:未定义的索引:收件人   /var/www/vhosts/partizanas.lt/httpdocs/brief/contactform.php上线   17注意:未定义的索引:receive0 in   /var/www/vhosts/partizanas.lt/httpdocs/brief/contactform.php上线   18注意:未定义索引:receive1 in   /var/www/vhosts/partizanas.lt/httpdocs/brief/contactform.php上线   19注意:未定义索引:receive2 in   /var/www/vhosts/partizanas.lt/httpdocs/brief/contactform.php上线   20注意:未定义索引:receive3 in   /var/www/vhosts/partizanas.lt/httpdocs/brief/contactform.php上线   21注意:未定义的索引:电子邮件   /var/www/vhosts/partizanas.lt/httpdocs/brief/contactform.php上线   22"

我写了修复错误的if条件:

if (isset($_POST['Submit']))    
{    

$formproc->AddRecipient($_POST["recipient"]); 
$formproc->AddRecipient($_POST["recipient0"]); 
$formproc->AddRecipient($_POST["recipient1"]); 
$formproc->AddRecipient($_POST["recipient2"]); 
$formproc->AddRecipient($_POST["recipient3"]);  
$formproc->AddRecipient($_POST["email"]); 
} 

但问题是,如果有空输入字段,则表单不会被发送。并且我希望它在不填写所有字段时发送表单。

有任何建议怎么做?

3 个答案:

答案 0 :(得分:1)

Check this answer

在将一个文件包含到另一个使用相同变量名的文件的情况下,依赖于未初始化变量的默认值是有问题的。打开register_globals也是一个主要的安全风险。如果使用未初始化的变量,则会发出E_NOTICE级别错误,但是在未初始化的数组中附加元素时则不会。 isset()语言构造可用于检测变量是否已经初始化。

答案 1 :(得分:1)

if (isset($_POST['Submit']))    
{    
if(isset($_POST["recipient"]) && $_POST["recipient"] !="" ){$formproc->AddRecipient($_POST["recipient"]);}
if(isset($_POST["recipient1"]) && $_POST["recipient"] !="" ){$formproc->AddRecipient($_POST["recipient1"]);}
if(isset($_POST["recipient2"]) && $_POST["recipient"] !="" ){$formproc->AddRecipient($_POST["recipient2"]);}
if(isset($_POST["recipient3"]) && $_POST["recipient"] !="" ){$formproc->AddRecipient($_POST["recipient3"]);}
$formproc->AddRecipient($_POST["email"]); 
} 

答案 2 :(得分:1)

考虑以下代码来解决您的问题:

if (isset($_POST['Submit']))    
{    

    if(!empty($_POST["recipient"])) {
        $formproc->AddRecipient($_POST["recipient"]); 
    }

    if(!empty($_POST["recipient0"])) {
        $formproc->AddRecipient($_POST["recipient0"]); 
    }

    if(!empty($_POST["recipient1"])) {
        $formproc->AddRecipient($_POST["recipient1"]); 
    }

    if(!empty($_POST["recipient2"])) {
        $formproc->AddRecipient($_POST["recipient2"]); 
    }

    if(!empty($_POST["recipient3"])) {
        $formproc->AddRecipient($_POST["recipient3"]);  
    }

    if(!empty($_POST["email"])) {
        $formproc->AddRecipient($_POST["email"]); 
    }
}

这里的想法是在输入字段为空时不执行AddRecipient()函数。 !empty()函数为你完成这项工作。