【发布时间】:2018-02-05 19:45:13
【问题描述】:
如果所有变量都继续进行文件处理,我需要检查它们是否满足要求。
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$s_id = $_POST['student_id'];
$tuition = $_POST['tuition'];
$payment = $_POST['payment'];
//Checking for Errors
if ($_SERVER["REQUEST_METHOD"] == "POST"){
//Checking Values
echo '<ul class="error">';
if(strlen($fname)<2){
echo '<li>'."First name must be 2 or more characters in length".'</li>';
}
if(strlen($lname)<3 || strlen($lname)>12){
echo '<li>'."Last name must be between 3 and 12 characters in length".'</li>';
}
if(strlen($s_id)!=9){
echo '<li>'."Student id must be exactly 9 characters in length".'</li>';
}
if($tuition < 2000 || $tuition > 10000){
echo '<li>'."Tuition must be between 2000 and 10000".'</li>';
}
echo '</ul>';
这部分工作,因为它应该报告遇到了什么错误。在此之后,如果输出成功消息并将数据放入文件中,我需要确保所有值都是正确的。
//Success
if($fname == true && $lname == true && $s_id == true && $tuition == true){
echo '<ul class="success">';
echo '<li>'."Payment Successful!".'</li>';
echo '</ul>';
//File Handling
$line = array($fname, $lname, $s_id, $tuition, $payment); //Creates a line to append to the file.
$handle = fopen("log.txt", "a+"); //Open for reading and writing; place the file pointer at the end of the file.
fputcsv($handle, $line); //Puts the values into the file.
fclose($handle); //Close the file.
}
}
我在检查所有变量是否满足我使用的if($fname == true && $lname == true && $s_id == true && $tuition == true) 的要求时遇到问题,但即使出现错误似乎也可以。我到底做错了什么?
【问题讨论】:
-
在脚本开头使用标志
$success = true;,然后在所有错误条件中添加$success = false;...然后在末尾而不是if($fname == true && $lname == true && $s_id == true && $tuition == true){,您现在只需使用if($success){ -
$s_id = '1'; var_dump($s_id == true); -
@Hackerman 谢谢。另一个简单的问题,格式是否可以,或者将 HTML 与 PHP 分开会更好吗?
-
既然你是这样用的,那就继续这样的编码方式,直到你掌握它……然后慢慢转向像
CodeIgniter这样的mvc框架……还有,另一种改进的方法您的代码避免使用多个echo语句...最好创建一个$errorMessage = ""变量,并在每个条件中使用字符串连接...并在最后回显变量,只需一次echo $errorMessage;
标签: php html if-statement fputcsv