2
<form action="http:\\127.0.0.1\rechecking.php" method="post" enctype="multipart/form-        data"><pre>
Enter your first Name: <input type="text" name="fname" size="15"></input>
Enter your Last Name:  <input type="text" name="lname" size="15"></input>
Your Email Id:         <input type="text" name="email" size="15"></input>
Your age:              <input type="text" name="age" size="1"></input> 
Upload your Image:     <input type="file" name="file"></input> 
<input type="Submit" value="Submit"></input></pre>
</form>


<?php
if(!empty($_POST["fname"])&&!empty($_POST["lname"])&&!empty($_POST["email"])&&!empty($_POST["age"]))
{
if($_FILES["file"]["error"]>0)
{
echo $_FILES['file']['error'] ."error is there in uploading files";
}
}
else
{         $emt=array($_POST['fname']=>"Firstname",$_POST['lname']=>"LastName",$_POST['email']=>"Email",$_POST['age']=>"Age");
foreach($emt as $value=>$variable)
{
if(empty($value))
{
echo $variable." cannot be left blank<br />";
}
}
}
?>

問題は、私のフォームですべてのスペースを空白のままにしておくと、連想配列の最後の要素しか表示されないことです。例:-Leave firstname,lastname,email, age の場合、「年齢フィールドを空白のままにすることはできません」と表示されます同様に、入力フィールドに年齢が既に入力されている場合は、「Email フィールドを空のままにすることはできません」空のままのすべてのフィールドの名前を表示したい

4

4 に答える 4

0

特定のキーが空かどうかを確認するには、最初にそれが設定されていることを確認する必要があります (ユーザーは HTML ソースを編集でき、一部のフィールドを送信できず、サイトでいくつかの警告がトリガーされます)。それ以外は、コードが少し乱雑であるため、しばらくするとデバッグや読み取りが困難になると思います。

ここでは、フィールドが入力されていて空でないことを確認するために PHP の部分を書き直しています。

<?php
$required = array(
  'fname' => 'First name', 
  'lname' => 'Last name', 
  'email' => 'Email address', 
  'age' => 'Age', 
);

$errors = array(); // Here, we store all the error messages. If it's empty, we are good to go. 

foreach ($required as $key => $label) {
  if (isset($_POST[$key]) || empty($_POST[$key])) {
    $errors[] = "$label field is required.";
  }
}
if (!isset($_FILES["file"])) {
  $errors[] = 'Please upload an image';
}
elseif (isset($_FILES['file']['error']) && $_FILES['file']['error']) {
  $errors[] = 'An error occurd while uploading your photo';
}

if ($errors) {
  print '<ul>';
  foreach ($errors as $error) {
    print "<li>$error</li>";
  }
  print '</ul>'
}
else {
  // All fields are filled and not empty, file is uploaded successfully. Process your form.
}
?>
于 2013-04-09T19:56:45.443 に答える