2013-12-11 42 views
1

我的php自我驗證表單提交給sql數據庫是否輸入表單字段的字符是否合適...如何阻止它提交,直到條件爲每個表單字段都符合?PHP表單提交給MySQL是否滿足驗證條件

<!DOCTYPE html> 
    <html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <title>RSG Contact Us</title> 
    <script> 
     //   $(function() { 
     //  $('form').on('submit', function (e) { 
      // $.ajax({ 
      //  type: 'post', 
      //  url: 'contact.php', 
      //  data: $('form').serialize(), 
      //   success: function() { 
        // alert('Thank you! your form has been submitted'); 
        //  } 
      //   }); 
      // e.preventDefault(); 
      // }); 
        // }); 
     </script> 
     </head> 
     <body> 
     <div id="contactuscall"> 
     <?php 
     function test_input($data) 
     { 
     $data = trim($data); 
     $data = stripslashes($data); 
     $data = htmlspecialchars($data); 
     return $data; 
     } 

     // define variables and set to empty values 
     $firstnameErr = $lastnameErr = $emailErr = $cellphoneErr = $genDerErr = $dognameErr = $BreedErr = $reasonErr = ""; 
     $firstname = $lastname = $email = $cellphone = $genDer = $dogname = $Breed = $reasoN= $freecomments = ""; 

     //if conditional statement stops PHP from looking for variable values until the submit button is hit 
     if ($_SERVER["REQUEST_METHOD"] == "POST") 
     { 
     // check if a first name was provided 
     if (empty($_POST["firstname"])) 
     {$firstnameErr = "A first name is required";} 
     else 
     { 
     $firstname = test_input($_POST["firstname"]); 
     // check if name only contains letters and whitespace 
     if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) 
     {$firstnameErr = "Only letters and white space allowed";} 
     } 
     //check if a last name was provided 
     if (empty($_POST["lastname"])) 
     {$lastnameErr = "A last name is required";} 
     else 
     { 
     $lastname = test_input($_POST["lastname"]); 
     // check if name only contains letters and whitespace 
     if (!preg_match("/^[a-zA-Z ]*$/",$lastname)) 
     { 
     $lastnameErr = "Only letters and white space allowed"; 
     } 
     } 
     // check if an email was provided 
    if (empty($_POST["email"])) 
     {$emailErr = "Email is required";} 
     else 
     { 
     $email = test_input($_POST["email"]); 
     // check if e-mail address syntax is valid 
     if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) 
     { 
     $emailErr = "Invalid email format"; 
     } 
     } 

     if (empty($_POST["cellphone"])) 
     {$cellphoneErr = "Please provide a phone number";} 
     else { 
     $cellphone = test_input($_POST["cellphone"]); 
     // Regular Expression to allow only valid phone number formats, including numbers, spaces, dashes, extensions 
     if (!preg_match("/^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/",$cellphone)) 
     {$cellphoneErr = "Invalid format";} 
     } 

     if (empty($_POST["dogname"])) 
     {$dognameErr = "A doggy name is required";} 
     else { 
     $dogname = test_input($_POST["dogname"]); 
     // check if dogname only contains letters and whitespace 
     if (!preg_match("/^[a-zA-Z ]*$/",$dogname)) 
     {$dognameErr = "Only letters and white space allowed";} 
     } 

     if (empty($_POST["Breed"])) 
     {$BreedErr = "A breed name is required";} 
     else { 
     $Breed = test_input($_POST["Breed"]); 
     // check if name only contains letters and whitespace 
     if (!preg_match("/^[a-zA-Z ]*$/",$Breed)) 
     {$BreedErr = "Only letters and white space allowed";} 
     } 

     if(empty($_POST['genDer'])) 
     {$genDerErr= "You forgot to select a Gender!";} 
     else { 
     $genDer=($_POST['genDer']); 
     } 

     //make sure one of the services requested checkboxes are checked 
     $reasoN = $_POST['reasoN']; 
     if(empty($reasoN)) 
     { 
     $reasonErr="You didn't select any services."; 
     } 
     else 
     { 
     $N = count($reasoN); 
     $reasonErr="You selected $N services(s): "; 
     } 

     // if comment section is not empty then run test_input function to purge possible malicious code 
     if (empty($_POST["freecomments"])) 
     {$freecomments = "";} 
     else 
     {$freecomments = test_input($_POST["freecomments"]);} 
     } 

     $host="fdb3.biz.nf"; //localhost 
     $dbuser="1546259_rsginfo"; //user 
     $dbpass="RSGnow12"; //pass 
     $dbname="1546259_rsginfo"; //db name 

    // Create connection 
    $conn=mysqli_connect($host,$dbuser,$dbpass,$dbname); 


// Check connection 
if (mysqli_connect_errno($conn)) 
    { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
    } 
//create query 
$sql= "INSERT INTO customer (fname, lname, email, phone, comments)VALUES ('$firstname', '$lastname', '$email', '$cellphone', '$freecomments')"; 
$sql2= "INSERT INTO DogInfo (DogName, Breed, Lookingfor)VALUES ('$dogname', '$Breed', '$reasoN')"; 

// execute query 
mysqli_query($conn,$sql); 
mysqli_query($conn, $sql2); 

// close connection 
mysqli_close($conn) 
?> 
    <form id="form1" name="form1" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>"> 
    <fieldset id="field1"> 
     <legend id="legend1">Contact info:</legend> 
     <hr /> 
     First name: <input type="text" id="firstname" name="firstname" size="30" class="textfield" value="<?php echo $firstname;?>"> 
     <span class="error">* <?php echo $firstnameErr;?></span> 
     E-mail: <input type="text" size="30" name="email" class="textfield" value="<?php echo $email;?>"> 
     <span class="error">* <?php echo $emailErr;?></span><br /> 
     Last name: <input type="text" id="lastname" name="lastname" size="30" class="textfield" value="<?php echo $lastname;?>"> 
     <span class="error">* <?php echo $lastnameErr;?></span>&nbsp;&nbsp;&nbsp;&nbsp; 
     Cell: <input type="text" id="cellphone" name="cellphone" size="30" class="textfield" value="<?php echo $cellphone;?>"> 
     <span class="error">* <?php echo $cellphoneErr;?></span><br /> 
    </fieldset> 
    <fieldset id="field2"> 
     <legend id="legend2">Doggie info:</legend> 
     <hr /> 
     Name: <input type="text" id="dogname" name="dogname" size="20" class="textfield" value="<?php echo $dogname;?>"><span class="error">* <?php echo $dognameErr;?></span> 
     Breed: <input type="text" id="Breed" name="Breed" size="20" class="textfield" value="<?php echo $Breed;?>"><span class="error">* <?php echo $BreedErr;?></span> 
    <p> 
     Gender:<select name="genDer" class="textfield"> 
      <option value="">--</option> 
      <option value="Intact Male" <?php echo isset($_POST['genDer']) && $_POST['genDer'] == "Intact Male" ? "selected" : "" ?>>Intact Male</option> 
      <option value="Neutered Male"<?php echo isset($_POST['genDer']) && $_POST['genDer'] == "Neutered Male" ? "selected" : "" ?>>Neutered Male</option> 
      <option value="Intact Female"<?php echo isset($_POST['genDer']) && $_POST['genDer'] == "Intact Female" ? "selected" : "" ?>>Intact Female</option> 
      <option value="Neutered Female"<?php echo isset($_POST['genDer']) && $_POST['genDer'] == "Neutered Female" ? "selected" : "" ?>>Neutered Female</option> 
      </select><span class="error">* <?php echo $genDerErr;?></span> 
    </p> 

    </fieldset> 
    <fieldset id="field3"> 
     <legend id="legend3">Services Required:</legend> 
     <hr /> 
     <input type="checkbox" name="reasoN[]" value="walkSale" 
     <?php if(isset($_POST['reasoN'])) echo "checked='checked'";?> class="textfield"/>I'm looking for a Dog Walker!&nbsp; 

     <input type="checkbox" name="reasoN[]" value="RawSale" 
     <?php if(isset($_POST['reasoN'])) echo "checked='checked'";?> class="textfield"/>I'm looking to purchase Raw Food!&nbsp; 

     <input type="checkbox" name="reasoN[]" value="groomSale" 
     <?php if(isset($_POST['reasoN'])) echo "checked='checked'";?> class="textfield"/>I'm looking for a Dog Groomer! 

     <span class="error">* <?php echo $reasonErr;?></span> 
     <?php echo $reasonConfirm;?> 

    </fieldset> 
    <fieldset id="field4"> 
     <legend id="legend4">Comments &amp; Questions</legend> 
     <hr /> 
     <textarea rows="7" cols="90" id="freecomments" name="freecomments"><?php echo $freecomments;?></textarea> 
    </fieldset> 
     <input id="submit" type="submit" name="submit" value="submit"> 
    </form> 
    </div> 
<?php 
echo "<h2>Your Input:</h2>"; 
echo $firstname; 
echo "<br>"; 
echo $lastname; 
echo "<br>"; 
echo $email; 
echo "<br>"; 
echo $cellphone; 
echo "<br>"; 
echo $dogname; 
echo "<br>"; 
echo $Breed; 
echo "<br>"; 
echo $genDer; 
echo "<br>"; 
echo $reasoN; 
echo "<br>"; 
echo $freecomments; 
?> 
</body> 
</html> 
+1

刪除您所有的,如果被驗證每個提交的崗位價值的陳述。將它們改爲僅將值賦給變量而不用'if'。 – Luke

+1

你應該放一個條件=>'如果(全部不是空的和/或有效的){//執行SQL}'*簡而言之*。你沒有一個(條件)包裝你的SQL。 –

回答

2

無論驗證是否成功,您的代碼實際上都會嘗試將值插入表中。最簡單和最快捷的解決方案是使用布爾標誌。

如:

// ... 
$formValid = true; // Define a boolean and set to true before validating 

//if conditional statement stops PHP from looking for variable values until the submit button is hit 
if ($_SERVER["REQUEST_METHOD"] == "POST") 
{ 
    // check if a first name was provided 
    if (empty($_POST["firstname"])) 
    { 
     $firstnameErr = "A first name is required"; 
    } else { 
     $firstname = test_input($_POST["firstname"]); 
     // check if name only contains letters and whitespace 
     if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) 
     { 
      $firstnameErr = "Only letters and white space allowed"; 
      $formValid = false; // Invalid input - set the flag to false 
     } 
    } 
} 
// .... 

// Eventually wrap the mysql logic inside a condition 
if ($formValid) 
{ 
    // Create connection 
    $conn=mysqli_connect($host,$dbuser,$dbpass,$dbname); 


    // Check connection 
    if (mysqli_connect_errno($conn)) 
     { 
     echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
     } 
    //create query 
    $sql= "INSERT INTO customer (fname, lname, email, phone, comments)VALUES ('$firstname', '$lastname', '$email', '$cellphone', '$freecomments')"; 
    $sql2= "INSERT INTO DogInfo (DogName, Breed, Lookingfor)VALUES ('$dogname', '$Breed', '$reasoN')"; 

    // execute query 
    mysqli_query($conn,$sql); 
    mysqli_query($conn, $sql2); 

    // close connection 
    mysqli_close($conn); 
} 
// ... rest of your code 
+0

很酷,所以我必須將虛警標誌添加到每個驗證條件語句中,對嗎? – Vynce82

+0

這樣做!非常感謝你killneel! – Vynce82