PHP忽略必填字段和提交表单

时间:2016-09-08 00:38:07

标签: php forms validation required requiredfieldvalidator

我有以下用PHP创建的表单,但出于某种原因,错误验证并不能阻止表单提交。我通常不是一个PHP开发人员,任何帮助将不胜感激。出于某种原因,我的多个选项的复选框也无效,并抛出错误

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>

<!DOCTYPE html>
<html lang="en">
<head>

  <!-- Basic Page Needs
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <meta charset="utf-8">
  <title>Submit Form</title>
  <meta name="description" content="">
  <meta name="author" content="">

  <!-- Mobile Specific Metas
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- FONT
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">

  <!-- CSS
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <link rel="stylesheet" href="css/normalize.css">
  <link rel="stylesheet" href="css/skeleton.css">

<script src='//cdn.tinymce.com/4/tinymce.min.js'></script>
  <script>
  tinymce.init({
    selector: '#PContent',
    theme: 'modern',
    height: 300,
    plugins: [
      'advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker',
      'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking',
      'save table contextmenu directionality emoticons template paste textcolor'
    ],
    content_css: 'css/content.css',
    toolbar: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | print preview media fullpage | forecolor backcolor emoticons'

  });
  </script>


  <!-- Favicon
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <link rel="icon" type="image/png" href="images/favicon.png">


<style>
form label {
    float: left;
    width: 150px;
    margin-bottom: 5px;
    margin-top: 5px;
}
.clear {
    display: block;
    clear: both;
    width: 100%;
}
</style>

</head>
<body onload="myUploadFunction()">
  <!-- Primary Page Layout
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <div class="container">
    <div class="row">
      <div class="one-half column" style="margin-top: 2%">


      <?php

 require 'xxx.php';

 $fnameErr = $emailErr = $genderErr = $websiteErr = "";

        // STEP 0. Are we getting form submission or should we show the form's field for filling?
         if(isset($_POST['add'])) {
           // STEP 1. Get the connection


            // STEP 2. Validate user's input

              if (empty($_POST["fname"])) {
    $fnameErr = "Name is required";
  } else {
    $fname = test_input($_POST["fname"]);
  }



        $lname = $_POST['lname'];  
        $phone = $_POST['phone'];  
        $email = $_POST['email'];  
        $doservice = $_POST['doservice'];  
        $etype = $_POST['etype'];  
        $rtype = $_POST['rtype'];  
        $ptime = $_POST['ptime'];  
        $paddress = $_POST['paddress'];  
        $rtime = $_POST['rtime'];  
        $daddress = $_POST['daddress'];  
        $vtype = $_POST['vtype'];  
        $pcount = $_POST['pcount'];  
        $addetails = $_POST['addetails'];  
        $heardwhere = $_POST['heardwhere'];  


            // STEP 3. Properly encode user input for SQL


            // STEP 4. Construct the SQL query


 //INSERT 
 $sql = " INSERT INTO QuotesInfo ( fname, lname, phone, email, doservice, etype, rtype, 
 ptime, paddress, rtime, daddress, vtype, pcount, addetails, heardwhere )  
 VALUES ('".$_POST["fname"]."','".$_POST["lname"]."','".$_POST["phone"]."','
".$_POST["email"]."','".$_POST["doservice"]."','".$_POST["etype"]."','".$_POST["rtype"]."','".$_POST["ptime"]."','
".$_POST["paddress"]."','".$_POST["rtime"]."','".$_POST["daddress"]."','".$_POST["vtype"]."','".$_POST["pcount"]."','
".$_POST["addetails"]."','".$_POST["heardwhere"]."') "; 


            //$retval = mysql_query( $sql, $mysqli ); // procedural version
            $retval = $mysqli->query($sql);

            // STEP 5. Execute the SQL query
            if(! $retval ) {
                // STEP 5.1 Deal with insuccess
               die('Could not enter data: ' . $mysqli->error);
            }

            // STEP 5.2 Deal with success
            echo "Entered data successfully\n";

$to = "myemail@gmail.com";
$subject = "Contact mail";
$from=$_POST["email"];
$msg= $fname . " " . $lname . "\r\n" . $phone . "\r\n" . $email . "\r\n" . $doservice . "\r\n" . $etype . "\r\n" . $rtype . "\r\n" . $ptime . "\r\n" . $paddress . "\r\n" . $rtime . "\r\n" . $daddress . "\r\n" . $vtype . "\r\n" . $pcount . "\r\n" . $addetails . "\r\n" . implode(",  ", $heardwhere);
$headers = "From: $from";

mail($to,$subject,$msg,$headers);
echo "Email successfully sent.";







            // STEP 6. We're done, close the connection
            //mysqli_close($mysqli);
            $mysqli->close();
         }else {
            ?>


<form id="form1" name="form1"  method = "post" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label for="fname">First Name</label><input type="text" name="fname" id="fname" />
 <span class="error">* <?php echo $fnameErr;?></span>
<br class="clear" /> 
<label for="lname">Last Name</label><input type="text" name="lname" id="lname" />
<br class="clear" /> 
<label for="phone">Phone</label><input type="text" name="phone" id="phone" />
<br class="clear" /> 
<label for="email">Email</label><input type="text" name="email" id="email" />
<br class="clear" /> 
<label for="doservice">Date of Service</label><input type="text" name="doservice" id="doservice" />
<br class="clear" /> 
<label for="etype">Event type</label><select name="etype" id="etype">
<option value="Wedding">Wedding</option>
<option value="Quinceanera/Cotillion">Quinceanera/Cotillion</option>
<option value="Corporate/Business">Corporate/Business</option>
<option value="Homecoming/Prom/School Dance">Homecoming/Prom/School Dance</option>
<option value="Bachelor/Bachelorette">Bachelor/Bachelorette</option>
<option value="Concert">Concert</option>
<option value="Sporting Event">Sporting Event</option>
<option value="Birthday">Birthday</option>
<option value="Sweet 16">Sweet 16</option>
<option value="Night Out">Night Out</option>
</select>
<br class="clear" /> 
<label for="rtype">Rental type</label><select name="rtype" id="rtype">
<option value="Hourly Rental">Hourly Rental</option>
<option value="Round Trip">Round Trip</option>
<option value="One Way">One Way</option>
<option value="Shuttle Service">Shuttle Service</option>
</select>
<br class="clear" /> 
<label for="ptime">Pickup Time</label><input type="text" name="ptime" id="ptime" />
<br class="clear" /> 
<label for="paddress">Pick Up Address and City</label><input type="text" name="paddress" id="paddress" />
<br class="clear" /> 
<label for="rtime">Return Time</label><input type="text" name="rtime" id="rtime" />
<br class="clear" /> 
<label for="daddress">Drop Off Address, City</label><input type="text" name="daddress" id="daddress" />
<br class="clear" /> 
<label for="vtype">Type of Vehicle</label><select name="vtype" id="vtype">
<option value="10 passenger limousine">10 passenger limousine</option>
<option value="22 Passenger SUV">22 Passenger SUV</option>
<option value="22-30 Passenger Party Bus">22-30 Passenger Party Bus</option>
<option value="31 Passenger Shuttle Bus">31 Passenger Shuttle Bus</option>
</select>
<br class="clear" /> 
<label for="pcount">How many passengers</label><input type="text" name="pcount" id="pcount" />
<br class="clear" /> 
<label for="addetails">Additional Details</label><textarea name="addetails" id="addetails" cols="45" rows="5"></textarea>
<br class="clear" /> 
<label for="heardwhere">How did you hear about us</label>
<input type="checkbox" name="heardwhere[]" value="Facebook" id="heardwhere_0" />Facebook
<input type="checkbox" name="heardwhere[]" value="Twitter" id="heardwhere_1" />Twitter
<input type="checkbox" name="heardwhere[]" value="Google" id="heardwhere_2" />Google
<input type="checkbox" name="heardwhere[]" value="Referral" id="heardwhere_3" />Referral
<input type="checkbox" name="heardwhere[]" value="Website Ad" id="heardwhere_4" />Website Ad
<input type="checkbox" name="heardwhere[]" value="Flyer" id="heardwhere_5" />Flyer
<input type="checkbox" name="heardwhere[]" value="Bridal Show" id="heardwhere_6" />Bridal Show
<input type="checkbox" name="heardwhere[]" value="Quinceanera Show" id="heardwhere_7" />Quinceanera Show
<input type="checkbox" name="heardwhere[]" value="Yelp" id="heardwhere_8" />Yelp
<input type="submit" name="add" id="add" value="Save">
<br class="clear" /> 
</form></div>



<div class="one-half column" style="margin-top: 2%">

<?php


$sqli = "SELECT fname, lname, phone, email, doservice, etype, rtype, ptime, paddress, rtime, daddress, vtype, pcount, addetails, heardwhere FROM QuotesInfo "; 

$resulti = $mysqli->query($sqli);

if ($resulti->num_rows > 0) {
    // output data of each row
    while($row = $resulti->fetch_assoc()) {
        echo "" . $row["fname"]. " " . $row["lname"]. " : " . $row["phone"]. "<br>"
. $row["email"]. " " . $row["doservice"]. " : " . $row["etype"]. "<br>"
. $row["rtype"]. " " . $row["ptime"]. " : " . $row["paddress"]. "<br>"
. $row["rtime"]. " " . $row["daddress"]. " : " . $row["vtype"]. "<br>"
. $row["pcount"]. " " . $row["addetails"]. " : " . $row["heardwhere"]. "<br>";
    }
} else {
    echo "0 results";
}



?>

</div>



     <?php
         }

         function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
      ?>




    </div>
  </div>
<!-- End Document
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
</body>
</html>

3 个答案:

答案 0 :(得分:0)

您在某种程度上验证输入,但在if / else语句中,如果未设置值,则需要进行某种转义,可能使用:     如果(!isset($值)){         错误[] ='值未设置';     }

If(isset($errors)){
    Echo your error handling
} else {
    The rest of your script
}

答案 1 :(得分:0)

你必须在你的if条件之后使用exit()函数

 if (empty($_POST["fname"])) {
    $fnameErr = "Name is required";
    exit();
}

现在这将首先检查你的fname,如果它是空的,它将退出

答案 2 :(得分:0)

  1. 你要做的第一件事就是把你所有的PHP代码放在一个Block中。我不知道你在做什么,你在第一个块中启动if条件并在另一个块中结束。
  2. 使用If else条件正确。我检查了你的代码,发现你启动了if条件,然后启动了其他条件,但之后又启动了另一个条件。好吧使用if else条件正确。
  3. 我在您的文件中发布了一些变量时更改了代码。检查这一点肯定会解决您的问题。 我已在我的系统上成功运行此代码。

     <?php
    

    $ fnameErr = $ emailErr = $ genderErr = $ websiteErr =“”;

        // STEP 0. Are we getting form submission or should we show the form's field for filling?
    

    //如果发布了fname          if(isset($ _ POST ['fname'])){            //步骤1.获取连接

            // STEP 2. Validate user's input
    
              if (empty($_POST["fname"])) {
    $fnameErr = "Name is required";
    

    } else {//否则condtion并记住你所有的if else条件应该是           //在这个区块中只是没有这个     $ fname = test_input($ _ POST [“fname”]);     $ lname = $ _POST ['lname'];
            $ phone = $ _POST ['phone'];
            $ email = $ _POST ['email'];
            $ doservice = $ _POST ['doservice'];
            $ etype = $ _POST ['etype'];
            $ rtype = $ _POST ['rtype'];
            $ ptime = $ _POST ['ptime'];
            $ paddress = $ _POST ['paddress'];
            $ rtime = $ _POST ['rtime'];
            $ daddress = $ _POST ['daddress'];
            $ vtype = $ _POST ['vtype'];
            $ pcount = $ _POST ['pcount'];
            $ addetails = $ _POST ['addetails'];
            $ hearwhere = $ _POST ['hearwhere'];

            // STEP 3. Properly encode user input for SQL
    
    
            // STEP 4. Construct the SQL query
    

    // INSERT  $ sql =“INSERT INTO QuotesInfo(fname,lname,phone,email,doservice,etype,rtype,  ptime,paddress,rtime,daddress,vtype,pcount,addetails,hearwhere)
     VALUES('“。$ $ POST [”fname“]。”','“。$ _ POST [”lname“]。”','“。$ _ POST [”phone“]。”',' “$ _ POST [ ”电子邮件“。” '' “$ _ POST [ ”doservice“。” '' “$ _ POST [ ”VLAN时“。” ''”。$ _ POST [ “舍入类型” ]。 “ ''”。$ _ POST [ “的ptime”。“ '' “$ _ POST [ ”paddress“。” '' “$ _ POST [ ”RTIME“。” '' “$ _ POST [ ”daddress“。” ''”。$ _ POST [ “V型” ]。 “ ''”。$ _ POST [ “pcount”。“ '' “。$ _ POST [”addetails“]。”','“。$ _ POST [”hearwhere“]。”')“;

            //$retval = mysql_query( $sql, $mysqli ); // procedural version
            $retval = $mysqli->query($sql);
    
            // STEP 5. Execute the SQL query
            if(! $retval ) {
                // STEP 5.1 Deal with insuccess
               die('Could not enter data: ' . $mysqli->error);
            }
    
            // STEP 5.2 Deal with success
            echo "Entered data successfully\n";
    

    $ to =“myemail@gmail.com”; $ subject =“联系邮件”; 从$ = $ _ POST [ “电子邮件”]; $ msg = $ fname。 “”。 $ lname。 “\ r \ n”。 $手机。 “\ r \ n”。 $ email。 “\ r \ n”。 $ doservice。 “\ r \ n”。 $ etype。 “\ r \ n”。 $ rtype。 “\ r \ n”。 $ ptime。 “\ r \ n”。 $ paddress。 “\ r \ n”。 $ rtime。 “\ r \ n”。 $ daddress。 “\ r \ n”。 $ vtype。 “\ r \ n”。 $ pcount。 “\ r \ n”。 $ addetails。 “\ r \ n”。 implode(“,”,$ hearwhere); $ headers =“From:$ from”;

    邮件($到,$主题,$味精,$头); echo“电子邮件已成功发送。”;

            // STEP 6. We're done, close the connection
            //mysqli_close($mysqli);
            $mysqli->close();
         }
       // this is your else condition, make sure it will be also in else 
      //condition above. I have commented this coz I have no database :P
         //else {
             $sqli = "SELECT fname, lname, phone, email, doservice, etype, rtype, ptime, paddress, rtime, daddress, vtype, pcount, addetails, heardwhere FROM QuotesInfo "; 
    

    $ resulti = mysqli_query($ con,$ sqli);

    if($ resulti-&gt; num_rows&gt; 0){     //输出每行的数据     while($ row = $ resulti-&gt; fetch_assoc()){         回声“”。 $行[ “FNAME”。 “”。 $行[“L-NAME”。 “:”。 $行[“电话”。 “
    ” 。 $行[“电子邮件”。 “”。 $行[ “doservice”。 “:”。 $行[“VLAN时”。 “
    ” 。 $行[“舍入类型”。 “”。 $行[ “的ptime”。 “:”。 $行[ “paddress”。 “
    ” 。 $行[ “RTIME”。 “”。 $行[ “daddress”。 “:”。 $行[“V型”。 “
    ” 。 $行[ “pcount”。 “”。 $行[ “addetails”。 “:”。 $行[ “heardwhere”。 “
    ”;     } } else {     echo“0结果”; }
           }

         function test_input($data) {
    

    $ data = trim($ data);   $ data = stripslashes($ data);   $ data = htmlspecialchars($ data);   返回$ data; }

            ?>
    
  4. 查看此代码并尝试理解它。希望这会现在奏效。快乐编码:)