简体   繁体   English

PHP 在另一页上处理的表单 - 但 PHP 验证不起作用

[英]PHP Form with process on another page - But PHP validation doesn't work

I've created a basic HTML form, and want to insert the form data into mysql database using php code.我创建了一个基本的 HTML 表单,并希望使用 php 代码将表单数据插入到 mysql 数据库中。 I've created 3 pages, one is index.php, second is process.php and third is config.php.我创建了 3 个页面,一个是 index.php,第二个是 process.php,第三个是 config.php。 My HTML form code is included in index.php as below:我的 HTML 表单代码包含在 index.php 中,如下所示:

    <form action="process.php" method="POST">
        <div>
            <label for="name">Name:</label><br />
            <input type="text" name="name" id="name"><br />
            <span class="error"><?php echo $nameErr; ?></span><br />
        </div>
        <div>
            <label for="email">Email:</label><br />
            <input type="text" name="email" id="email"><br />
            <span class="error"><?php echo $emailErr; ?></span><br />
        </div>
        <div>
            <label for="message">Message:</label><br />
            <textarea name="message" id="message" cols="22" rows="10"></textarea>
        </div>
        <br />
        <input type="submit" name="submit" value="Submit">  
    </form>

my PHP code for form validation and inserting data into database is included in process.php.我的 PHP 用于表单验证和将数据插入数据库的代码包含在 process.php 中。 and my code for connecting to database is included in config.php.我连接到数据库的代码包含在 config.php 中。 The problem is that, when I correctly fill the form fields, It works perfectly, form is submitted, and insert data into database.问题是,当我正确填写表单字段时,它完美地工作,提交表单并将数据插入数据库。 But when I wrongly fill the form fields, instead of showing me the validation messages below the each field and stopping me on the index.php page until I fill all the fields correctly, It redirects me to blank process.php page.但是当我错误地填写表单字段时,它没有向我显示每个字段下方的验证消息并在 index.php 页面上停止我直到我正确填写所有字段,它会将我重定向到空白 process.php 页面。

I want, when I fill the wrong field, It should show me an alert message below the field, and should stop me on index.php page until I fill all the fields correctly.我想,当我填写错误的字段时,它应该在字段下方显示一条警告消息,并且应该在 index.php 页面上阻止我,直到我正确填写所有字段。

Thanks,谢谢,

What you do now is:你现在要做的是:

  1. load index.php负载index.php
  2. include process.php包括process.php
  3. there is no $_POST data, so it skips the checking and displays the form没有$_POST数据,所以它跳过检查并显示表单

Then you post the form to process.php :然后将表单发布到process.php

  1. load process.php加载process.php
  2. check $_POST检查$_POST
  3. if data is ok: echo succes message, or fail on error inserting如果数据正常:回显成功消息,或因错误插入而失败
  4. if data not ok: you reach the end of the script and do nothing, resulting in a blank page如果数据不正常:你到达脚本的末尾并且什么都不做,导致一个空白页面

What you should do is point the form to index.php你应该做的是将表格指向index.php

  1. load index.php负载index.php
  2. include process.php only if there is $_POST data仅当有$_POST数据时包括process.php
  3. check $_POST检查$_POST
  4. if ok: echo message and DIE如果正常:回显消息和 DIE
  5. if not ok: set errors如果不行:设置错误
  6. display the form (again, including the errors)显示表单(同样,包括错误)

So index.php should look like:所以index.php应该是这样的:

<?php
$name = $email = $message = "";
$nameErr = $emailErr = "";

//If there is $_POST data, do the check
if ($_SERVER['REQUEST_METHOD'] == "POST") {
   // load process.php only if needed
   require_once "process.php";
   //... do the testing
   
   if (empty($nameErr) && empty($emailErr)) {
      // load config.php only if needed
      require_once "config.php";
      //... insert into db
      if ($stmt -> execute()) {
         //SHOW a SUCCESS message and STOP
         echo ...;
         die;
         }
      else {
        //show a FAIL message and STOP
        echo ...;
        die;
        }
      }

   }

?>
//At this point, there is either no POST data (first time load), or you checked the data and there are errors. So you DISPLAY THE FORM (again), including errors.
<form action="index.php" method="POST">
....
</form>

I assume your form is in index.php .我假设您的表格在index.php中。 First of all, you should make a form and check if there's anything stored in session as error message or not to show errors:首先,您应该制作一个表格并检查 session 中是否存储了任何内容作为错误消息或不显示错误:

<?php
// index.php
session_start();
$emailErr = isset($_SESSION['error_email']) ? $_SESSION['error_email'] : '';
$messageErr = isset($_SESSION['error_message']) ? $_SESSION['error_message'] : '';
$nameErr = isset($_SESSION['error_name']) ? $_SESSION['error_name'] : '';
?>
<form action="process.php" method="POST">
    <div>
        <label for="name">Name:</label><br />
        <input type="text" name="name" id="name" value="<?php echo $name; ?>"><br />
        <span class="error"><?php echo $nameErr; ?></span><br />
    </div>
    <div>
        <label for="email">Email:</label><br />
        <input type="text" name="email" id="email" value="<?php echo $email; ?>"><br />
        <span class="error"><?php echo $emailErr; ?></span><br />
    </div>
    <div>
        <label for="message">Message:</label><br />
        <textarea name="message" id="message" cols="22" rows="10"><?php echo $message; ?></textarea>
        <span class="error"><?php echo $messageErr; ?></span><br />
    </div>
    <br />
    <input type="submit" name="submit" value="Submit">  
</form>

Now you should process your form in process.php and set desired session errors for non-validated fields:现在您应该在process.php中处理您的表单,并为未验证的字段设置所需的 session 错误:

// process.php
session_start();
unset($_SESSION['error_email'], $_SESSION['error_message'], $_SESSION['error_name']);
if ($_SERVER['REQUEST_METHOD'] == "POST") {
    $valid = true;
    $input_name = test_input($_POST['name']);
    if (empty($input_name)) {
        $_SESSION['error_name'] = "Please enter a name!";
        $valid = false;
    } elseif (!preg_match("/^[a-zA-Z ]*$/", $input_name)) {
        $_SESSION['error_name'] = "Only letters and white spaces are allowed!";
        $valid = false;
    } else {
        $name = $input_name;
    }
    $input_email = test_input($_POST['email']);
    if (empty($input_email)) {
        $_SESSION['error_email'] = "Please enter an email address!";
        $valid = false;
    } elseif (!filter_var($input_email, FILTER_VALIDATE_EMAIL)) {
        $_SESSION['error_email'] = "Invalid email address!";
        $valid = false;
    } else {
        $email = $input_email;
    }

    $input_message = test_input($_POST['message']);
    if (empty($input_message)) {
        $_SESSION['error_message'] = "Please enter your message!";
        $valid = false;
    } else {
        $message = $input_message;
    }

    if ($valid) {
        $sql = "INSERT INTO users (name, email, message) VALUES (?, ?, ?)";

        if ($stmt = $conn -> prepare($sql)) {
            $stmt -> bind_param("sss", $param_name, $param_email, $param_message);

            $param_name = $name;
            $param_email = $email;
            $param_message = $message;

            if ($stmt -> execute()) {
                echo "<p style='color:green'>Thank you for submitting the form! We'll get back to you soon.</p>";
                echo "<a href='index.php'>Go back</a>";
            } else {
                echo "<p style='color:red'>Something went wrong! Please try again later.</p>";
            }
        }
        $stmt -> close();
        $conn -> close();
    } else {
        $conn -> close();
        header('Location: index.php');
        exit('<meta httpd-equiv="Refresh" content="0;url=index.php"/>');
    }
}

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

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

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