简体   繁体   English

苦苦进行表单验证而不执行PHP

[英]Struggling with form validation not executing PHP

Hello Guy's please assist, am having validation problem. 您好,盖伊,请提供协助,遇到验证问题。 so basically if i don't validate any of the form the form execute perfectly, how ever once i validate it the form just returned with form and it value. 因此,基本上,如果我不验证任何形式的表单都可以完美执行,那么一旦我验证了表单,表单又会返回它的值。

** here is my code ** **这是我的代码**

             $error[] = "";
         if (isset($_POST['submit'])) {

             $firstname = trim($_POST['firstname']);
             $lastname = trim($_POST['lastname']);
             $user_name = trim($_POST['user_name']);
             $user_type = trim($_POST['user_type']);
             $email = trim($_POST['email']);
             $created_at = trim($_POST['created_at']);
             $password = trim($_POST['password']);
             $confirm_password = trim($_POST['confirm_password']);

             // validate form field
             if (empty($firstname)) {
                 $error[] = 'Field empty, please enter your first name';
             } else {
                 if (strlen($firstname) < 3) {
                     $error[] = 'First Name is too short';
                 }
             }
             // check if name only contains letters and whitespace
             if (!preg_match("/^[a-zA-Z ]*$/", $firstname)) {
                 $error[] = "Only letters and white space allowed";
             }
             if (empty($lastname)) {
                 $error[] = 'Field empty, please enter your last name';
             } else {
                 if (strlen($lastname) < 3) {
                     $error[] = 'Last Name is too short';
                 }
             }
             // check if name only contains letters and whitespace
             if (!preg_match("/^[a-zA-Z ]*$/", $lastname)) {
                 $error[] = "Only letters and white space allowed";
             }
             if (empty($user_name)) {
                 $error[] = 'Field empty, please enter your username';
             } else {
                 if (strlen($user_name) < 3) {
                     $error[] = 'UserName is too short';
                 }
             }
             // set email filter validation 
             if (empty($email)) {
                 $error[] = 'Field empty, please enter your email address';
             } else {
                 //email validation
                 if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
                     $error[] = 'Please enter a valid email address';
                 }
             }
             if (empty($password)) {
                 $error[] = 'Field empty, please create a password';
             } else {
                 if (strlen($password) < 6) {
                     $error[] = 'Password is too short';
                 }
                 if (strlen($password) > 15) {
                     $error[] = 'Password is too long';
                 }
                 if (!preg_match("#[A-Z]+#", $password)) {
                     $error[] = "Password must include at least one CAPS! ";
                 } else {
                     if (!preg_match("#[0-9]+#", $password)) {
                         $error[] = "Password must include at least one NUMBER! ";
                     }
                 }
             }
             // set field validation for confirm password
             if (empty($confirm_password)) {
                 $error[] = 'Field empty, please confirm your password';
             } else {
                 if ($password != $confirm_password) {
                     $error[] = 'Error... Passwords do not match';
                 }
             }

             //if no errors have been created carry on
             if (!isset($error)) {

                 $password_hash = password_hash($password, PASSWORD_DEFAULT);
                 $created_at = date('Y-m-d');
                 if (!($stmt = $con - > prepare("INSERT INTO user (firstname, lastname, user_name, user_type, email, password, created_at) 
                             VALUES( ? , ? , ? , ? , ? , ? , ? )
                             "))) {
                             echo "Prepare failed: (".$con - > errno.
                             ")".$con - > error;
                         }
                         if (!$stmt - > bind_param('sssssss', $firstname, $lastname, $user_name, $user_type, $email, $password_hash, $created_at)) {
                             echo "Binding paramaters failed:(".$stmt - > errno.
                             ")".$stmt - > error;
                         }
                         if (!$stmt - > execute()) {
                             echo "Execute failed: (".$stmt - > errno.
                             ")".$stmt - > error;
                         }
                         $stmt - > close();
                         if ($stmt) {
                             $_SESSION['main_notice'] = "Successfully registered, login here!";
                             header('Location: index.php');
                             exit;
                         } else {
                             $_SESSION['main_notice'] = "Some error, try again";
                             header('Location: '.$_SERVER['PHP_SELF']);
                         }
                     }
                 }

I don't no if you can see what i can't am not seeing. 如果您能看到我看不到的东西,我不会。 Thanks in advance. 提前致谢。

isset checks that varialbe is set that is it has a value isset检查是否已设置 varialbe 是否 it has a value

Your if(!isset($error)){ will never be true . 您的if(!isset($error)){将永远不会为true Because you set value for $error earlier in your script: 因为您在脚本的前面为$error设置了值,所以:

$error[] = "";

This line is wrong too. 这条线也是错误的 You add an empty string to $error . 您将一个空字符串添加到$error Why? 为什么? Just declare it as empty array: 只需将其声明为空数组即可:

$error = [];

After that you can check emptiness of $error witn empty() instead of isset : 之后,您可以检查$error empty()而不是isset

//if no errors have been created carry on
if(empty($error)) { 

I would suggest laying it out slightly different. 我建议布局略有不同。

First perform the checks when you detect the form has been posted. 当您检测到表单已过帐时,请首先执行检查。 If you do this before any content is output you can still send headers and perform other useful actions. 如果在输出任何内容之前执行此操作,您仍然可以发送标题并执行其他有用的操作。

$sError     = ""; 
$sFirstName = '';

// check if post has been made
if(isset($_POST['submit'])){

    //check for content and a non empty string
    if(isset($_POST['FirstName']) && $_POST['FirstName'] != ''){

        // perform any other validation tasks here
        if(strlen($_POST['FirstName'] > 3){

            $sFirstName = $_POST['FirstName'];
        }else{
             $sError .= "[FirstNameLength]";
        }

    }

    // if firstname hasnt been set we can add to error string
    if($sFirstName == '')
       $sError .= "[FirstName]";


    // if nothing in sError go ahead with the action 
    if($sError = ""){

    }

Then later after you have included your header etc, you can check the sError var and output any error messages; 然后,在包含标头等之后,您可以检查sError var并输出任何错误消息;

if($sError !== ""){
    if( 
        strpos($sError, '[FirstName]') !== false ||
        strpos($sError, '[LastName]') !== false
    ){
        echo"<div class=\"statusMessage alert alert-danger\" role=\"alert\"><ul>";

        if(strpos($sError, '[FirstName]') !== false){
            echo "<li>You must enter a first name</li>";
        }
        if(strpos($sError, '[FirstNameLength]') !== false){
            // just an example of another check, firstname could be 1 char!
            echo "<li>Your first name is too short, please enter full name</li>";
        }

        echo "</ul></div>";
    }
}




// success messages
if(isset($_GET['successMessage'])){
    if($_GET['successMessage'] === "info-updated"){
        echo"<div>Info Updated.</div>";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM