插入数据库之前的表单验证逻辑

时间:2015-06-17 07:08:46

标签: php forms validation

我想在插入数据库之前编写一个数据验证逻辑。如果数据无效,那么它会提示用户错误,但后来我面临的问题不是我希望的逻辑: (1)消息"数据已成功插入!"显示甚至错误检查消息是提示。 (2)消息"数据已成功插入!"如果没有在表格中输入数据,则单击“提交”。

我应该如何将逻辑更改为我希望拥有的逻辑?

<?php
// Initialize variables to null.
$comp_nameError ="";
$compLicenseeNameError ="";

if(isset($_POST['comp_name']))  {$comp_name= $_POST['comp_name'];}
if(isset($_POST['comp_licensee_name'])) {$comp_licensee_name= $_POST['comp_licensee_name'];}

//On submitting form below function will execute
if (isset($_POST['submit'])) {

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

    //-------------------------Form Validation Start---------------------//
   if (empty($_POST["comp_name"])) {
     $comp_nameError = "Name is required";
   } else {
     $comp_name = test_input($_POST["comp_name"]);
     // check name only contains letters and whitespace
     if (!preg_match("/^[a-zA-Z ]*$/",$comp_name)) {
       $comp_nameError = "Only letters and white space allowed"; 
     }
   }

   if (empty($_POST["comp_licensee_name"])) {
     $compLicenseeNameError = "Company Licensee Name is required";
   } else {
     $comp_licensee_name = test_input($_POST["comp_licensee_name"]);
   }
   //-------------------------Form Validation End---------------------//


    // attempt a connection
    $host="host=xx.xx.xx.xx";
    $port="port=xxxx";
    $dbname="dbname=xxxx";
    $credentials="user=xxxxxx password=xxxxxxx";

    $dbh = pg_connect("$host $port $dbname $credentials");
    if (!$dbh) {
        die("Error in connection: " . pg_last_error());
    }

    // execute query
    $sql = "INSERT INTO t_comp(comp_name, comp_licensee_name)VALUES('$comp_name', '$comp_licensee_name')";
    $result = pg_query($dbh, $sql); 

    if (!$result) {
        die("Error in SQL query: " . pg_last_error());
    }
    echo "Data successfully inserted!";

    // free memory
    pg_free_result($result); 

    // close connection
    pg_close($dbh);
}
//php code ends here 
?>


<html>
    <head>

    <link rel="stylesheet" href="style/style.css" />
    </head>
    <body>

        <div class="maindiv">
            <div class="form_div">    
            <form method="post" action="compReg.php">                   
                <span class="error">* required field.</span>

                <br>
                <hr/>
                <br>
                Company Name:<br><input class="input" type="text" name="comp_name" value="">
                <span class="error">* <?php echo $comp_nameError;?></span>
                <br>         

                Company Licensee:<br><input class="input" type="text" name="comp_licensee_name" value="">
                <span class="error">* <?php echo $compLicenseeNameError;?></span>
                <br>    

                <input class="submit" type="submit" name="submit" value="Submit"> 
            </form>
            </div>          
        </div>
    </body>
</html>

2 个答案:

答案 0 :(得分:0)

我将错误累积到一个数组中,只有在它被清空时才进入插入部分:

$errors = array();
if (empty($_POST["comp_name"])) {
    $errors[] = "Name is required";
} else {
    $comp_name = test_input($_POST["comp_name"]);
    // check name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$comp_name)) {
        $errors[] = "Only letters and white space allowed in the computer name"; 
    }
}

if (empty($_POST["comp_licensee_name"])) {
    $errors[] = "Company Licensee Name is required";
} else {
    $comp_licensee_name = test_input($_POST["comp_licensee_name"]);
}

if (!empty($errors)) {
    echo "The following errors occurred:<br/>" . implode('<br/>', $errors);
    exit();
}

// If we didn't exit, continue to the insertion code

答案 1 :(得分:0)

    <?php
    // Initialize variables to null.
   $comp_nameError ="";
   $compLicenseeNameError ="";

    if(isset($_POST['comp_name']))  {$comp_name= $_POST['comp_name'];}
       if(isset($_POST['comp_licensee_name'])) {
             $comp_licensee_name= $_POST['comp_licensee_name'];}

           //On submitting form below function will execute
             if (isset($_POST['submit'])) {

                // check boolean variable value 
                $is_valid = 1;

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

     //-------------------------Form Validation Start---------------------//
      if (empty($_POST["comp_name"])) {
          $comp_nameError = "Name is required";
          } else {
            $comp_name = test_input($_POST["comp_name"]);
          // check name only contains letters and whitespace
           if (!preg_match("/^[a-zA-Z ]*$/",$comp_name)) {
             $validation_error = "Only letters and white space allowed"; 
               $is_valid = 0;
           }
     }

        if (empty($_POST["comp_licensee_name"])) {
           $validation_error = "Company Licensee Name is required";
           $is_valid =0;
          } else {
             $comp_licensee_name = test_input($_POST["comp_licensee_name"]);
            }
          //-------------------------Form Validation End---------------------//


        // attempt a connection
  if($is_valid == 1 ){
    $host="host=xx.xx.xx.xx";
    $port="port=xxxx";
    $dbname="dbname=xxxx";
    $credentials="user=xxxxxx password=xxxxxxx";

    $dbh = pg_connect("$host $port $dbname $credentials");
    if (!$dbh) {
        die("Error in connection: " . pg_last_error());
    }

    // execute query
    $sql = "INSERT INTO t_comp(comp_name, comp_licensee_name)VALUES('$comp_name', '$comp_licensee_name')";
    $result = pg_query($dbh, $sql); 

    if (!$result) {
        die("Error in SQL query: " . pg_last_error());
    }
    echo "Data successfully inserted!";

    // free memory
    pg_free_result($result); 

    // close connection
    pg_close($dbh);
} else {
     echo $validation_error; 
     die;
}
 }
 //php code ends here 
?>