简体   繁体   English

使用 php 以 html 形式显示错误消息

[英]Displaying error message in html form with php

I would like to display error messages in my html form through php variables which are populated with the values which are assigned in 'register-form_v2.php'.我想通过 php 变量在我的 html 表单中显示错误消息,这些变量填充了在“register-form_v2.php”中分配的值。

Could someone enlighten me why the variables, which I would like to echo out in the form do not hold any values?有人能告诉我为什么我想在表格中回显的变量不包含任何值吗? Because when I submit the form I don't get the desired error messages displayed to the user, it simply directs me to the url defined in the if statement, but nothing more.因为当我提交表单时,我没有向用户显示所需的错误消息,它只是将我定向到 if 语句中定义的 url,但仅此而已。

Below the file with the html form and the variable / error message I would like to echo out.在带有 html 表格的文件下方以及我想回显的变量/错误消息。

<?php

include "register-form_v2.php";

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <style>
        #wrapper {
            width: 100%;
            margin: 0 auto;
            background-color: aliceblue;
        }

        form {
            display: flex;
            flex-direction: column;
            width: 50%;
            margin: auto;
            padding: 20px;
            background-color: antiquewhite;
        }

        .input-wrapper {
            margin: 20px;
            font-size: 20px;
        }

        .red-text {
            color: red;
        }

    </style>
    
    <div id="wrapper">

        <form action="register-form_v2.php" method="POST">
        
        <div class="red-text" ><?php echo $errors['email'];?> Test, this displays :=)</div>
            <div class="input-wrapper">
                <label for="email">E-mail</label> <br>
                <input id="email" type="text" name="email" value="">
            </div>
            <div class="red-text" ><?php echo $errors['username'];?></div>
            <div class="input-wrapper">
                <label for="username">Username</label> <br>
                <input type="text" name="username" value="">
            </div>
            <div class="red-text" > <?php echo $errors['password']; ?></div>
            <div class="input-wrapper" >
                <label for="password">Password</label> <br>
                <input type="text" name="password" value="">
            </div>
            <div class="red-text" > <?php echo $errors['password']; ?></div>
            <div class="input-wrapper">
                <label for="password-check">Password-check</label> <br>
                <input type="text" name="password-check" value="">
            </div>

            <div class="input-wrapper">
                <button type="submit" name="login-submit">Login</button>
            </div>

        </form>

    </div>

</body>
</html>

The 2nd file with my form validation.带有我的表单验证的第二个文件。

<?php

$errors = array('fields' => '', 'email' => '', 'username' => '', 'password' => '');
$fields_err = '';

if($_SERVER["REQUEST_METHOD"] == "POST") {

    require "dbConnect.php";
    
   
    
    $email = $_POST["email"];
    $username = $_POST["username"];
    $password = $_POST["password"];
    $password_check = $_POST["password-check"];

    
    

    if( empty($email) || empty($username) || empty($password) || empty($password_check)) {
        header("location: SignUp.php?error=emptyfields&mail=".$email."&uid=".$username);
        $errors['fields'] = 'You need to fill in the fields';
        $fields_err = ' doh it went wrong no fields ';
        echo 'asdfasdf';
    }
    //checking for valid email
    elseif(!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/", $username)) {
        $errors['email'] = 'please use a valid email and user ID, user ID can only use alphanummeric values';
        header("location: SignUp.php?error=invalidmail_and_uid");
        exit();
        //cjecl
    } elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors['email'] = 'something not right there with your email budy';
        header("location: SignUp.php?error=invalidmail&uid=".$username);
        exit();
    }
    // checking for valid username
    elseif(!preg_match("/^[a-zA-Z0-9]*$/", $username)) {
        $errors['username'] = 'your username is invalid, your username needs to include only numbers or letters';
        header("location: SignUp.php?error=invalidUid&mail=".$email);
        exit();
    }
    //checking for password length
    elseif(strlen(trim($password)) < 11) {
        $errors['password'] = 'your password must include at least 11 characters';
        header("location: SignUp.php?error=nopswMatch&uid=".$username."&mail=".$email);
        exit();
    }
    //checking if password and password_check match
    elseif($password !== $password_check) {
        $errors['password'] = 'your password confirmation does not match';
        header("location: SignUp.php?error=nopswMatch&uid=".$username."&mail=".$email);
        exit();
    } else {
        $sql = "SELECT username FROM dudes WHERE username=:username";
    
                //check if username is already taken
        if(!$stmt = $conn->prepare($sql)) {
 
            //Bind variables to the prepared statemnet as parameters
            header("location: SignUp.php?error=sqlerror");
            exit();
        } else {

            $stmt->bindParam(":username", $username, PDO::PARAM_STR);
            $stmt->execute();
            
            $result_check = $stmt->rowCount();

            if($result_check == 1) {
                $errors['username'] = 'the user name has already been taken';
                echo "The userName has already been taken";
            } 
            else {
                echo "great success";
                // insert code here
                $sql = "INSERT INTO dudes (email, username, password) VALUES (:email, :username, :password)";

                if(!$stmt = $conn->prepare($sql)) {
                    header("location: SignUp.php?error=prepStmtFail");
                } else {
                    $stmt->bindParam(':email', $email);
                    $stmt->bindParam(':username', $username);
                    $stmt->bindParam(':password', $param_password);
                    // hash the password
                    $param_password = password_hash($password, PASSWORD_BCRYPT);

                if($stmt->execute()){

                    header("location: SignUp.php?signup=success");
                    exit();
                }
                
                }

            

            }
        }
    }
}

?>

You can temporary store your error in $_SESSION variable.您可以将错误临时存储在 $_SESSION 变量中。 Or you can add your error in the $_GET variable或者您可以在 $_GET 变量中添加您的错误

Example:例子:

// php part :
session_start();

$_SESSION['errors']['password'] = 'your password confirmation does not match';
header("location: SignUp.php?error=nopswMatch&uid=".$username."&mail=".$email);

// html part : 
if(isset($_SESSION['errors'])) {
    foreach ($_SESSION['errors'] as $key => $value) {
        echo '<div class="red-text" >'. $_SESSION['errors']['email']. 'Test, this displays :=)</div>';
    }
}
unset($_SESSION['errors']);

OR或者

// php part :
header("location: SignUp.php?error=your password confirmation does not match&uid=".$username."&mail=".$email);


// html part : 
if(isset($_GET['error'])) {
    echo '<div class="red-text" >'. $_GET['error']. 'Test, this displays :=)</div>';
}

A variable value can be used in a single page only.变量值只能在单个页面中使用。 Since you populated the $error array in another php file you can't use that variable in other pages.由于您在另一个 php 文件中填充了 $error 数组,因此您不能在其他页面中使用该变量。

What you could do is use a $_SESSION[] variable which is accessible in any pages that uses session_start() at top of the code.您可以做的是使用 $_SESSION[] 变量,该变量可在代码顶部使用 session_start() 的任何页面中访问。

Or use this in your login or signup page或者在您的登录或注册页面中使用它

<?php

if(isset($_GET['error']) && $_GET['error']=='emptyfield')
{
 $errors['email'] = 'All field are compulsory";
}
?>

Now you can use $errors['email'] in your form现在您可以在表单中使用 $errors['email']

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

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