使表单字段非空,并使用php从涉及一些空字段的表单数据计算平均值

时间:2015-02-05 18:51:27

标签: php arrays foreach count

我一直在尝试:(i)使用php脚本使我的表单字段非空 (ii)计算插入数组的数值形式数据的平均值,并且数组的元素可以为空。例如,假设表格用于收集学生的分数,某些学生可能不会提供选修科目。如何在这个实例中调整count()数组函数是我的头疼。我承认有些人提出的问题部分解决了这个问题,但有些问题仍然没有解决,因此这篇文章。 总结:(i)即使某些表单字段为空,也符合我的意愿,下面的代码也会执行。(ii)如果我授予某些表单字段为空;平均计算结果不正确;也违背了我的意愿 代码:

<?php
$name = $_POST['candidate'];
$Eng_CA = $_POST['Eng_CA'];
$Eng_Ex = $_POST['Eng_Ex'];
$Math_CA = $_POST['Math_CA'];
$Math_Ex = $_POST['Math_Ex'];
$Comp_CA = $_POST['Comp_CA'];
$Comp_Ex = $_POST['Comp_Ex'];
$engSum = $Eng_CA + $Eng_Ex;
$mathSum = $Math_CA + $Math_Ex;
$compSum = $Comp_CA + $Comp_Ex;
$tot = array();
$tot[] = $engSum;
 $tot[]=  $mathSum;
$tot[] = $compSum;
 $total = array_sum($tot);
 $Average = $total/count($tot); // Average is incorrcet if some fields are empty
$notEmpty = array();

$notEmpty = array('$name', '$Eng_CA', '$Eng_Ex', '$Math_CA', '$Math_Ex', '$Comp_CA', '$Comp_Ex');

foreach ($notEmpty as $notEmp){ // this is not working; code executes anyway

HTML

<form action ='test_Code.php' method ='post'>
<table width ='600'>
<tr><td> Cand Name</td><td colspan ='2'><input type ='text' name = 'candidate' size = '60'></td></tr>
<th>Subject</th><th>CA</th><th>Exam</th>

<tr><td>Eng</td><td><input type ='text' name = 'Eng_CA'/></td><td><input type ='text' name = 'Eng_Ex'/></td></tr>

<tr><td>Math</td><td><input type ='text' name = 'Math_CA'/></td><td><input type ='text' name = 'Math_Ex'/></td></tr>

<tr><td>Computer</td><td><input type ='text' name = 'Comp_CA'/></td><td><input type ='text' name = 'Comp_Ex'/></td></tr>

if(empty($notEmp)){
    echo"You have left some fields empty, fill them pls";
die();

}

}
echo"<table border ='1'>";
echo"<th>Candidate</th><th>Eng Ca</th><th>Eng Ex</th><th>Math Ca</th> <th>Math Ex</th> <th>Comp Ca</th><th>Comp ex</th><th>Total</th><th>Average</th>";
echo"<tr><td>";
echo $name ."</td><td>".$Eng_CA."</td><td>".$Eng_Ex."</td><td>".$Math_CA."</td><td>".$Math_Ex."</td><td>".$Comp_CA."</td><td>". $Comp_Ex."</td><td>".$total."</td><td>".$Average."</td></tr></table>";

?>

1 个答案:

答案 0 :(得分:2)

你试图以奇怪的方式对我进行一次非空检查。我个人会做的只是首先循环你的$ _POST变量。检查它们是否为空。如果这样死或错误。例如:

    <?php
    if(!empty($_POST)): //this is how trigger the processes for any form

    foreach($_POST as $k => $v):
       if(empty($v)){
            echo $k.' can not be blank.<br>';
            $error .= '<div>'.$k.' can not be blank.</div>'; //here is another option...  

       }
    endforeach;
    //if you get here now do your averages or whatever you were wanting.

    endif;

//anywhere else in your entire php page write this
if($error){echo $error; } //this is a basic check, if error is empty it will be false, if error is not empty above it will print out the fields that

   ?>