PHP表单验证助手

时间:2016-08-03 14:12:38

标签: php forms validation mysqli

我真的需要帮助。我知道我有类似的帮助,但试过没有运气。

使用PHP和Mysqli程序创建具有用户类型的注册系统。我刚开始使用PHP,所以请耐心等待。

我需要有关表单验证的帮助......它看起来对我很好,但错误没有处理。下面是我的注册码和errMsg代码。

连接代码:            

    define('HOST','localhost');
    define('USERNAME','');
    define('PASSWORD','');
    define('DBNAME','');
    $con=mysqli_connect(HOST,USERNAME,PASSWORD,DBNAME)or die('ERROR WHILE CONNECTING TO DATABASE SERVER');
    ?>

注册和错误代码

    <?php
    session_start(); 
    if(is_file('include/connection.php'))
    include_once('include/connection.php');
    else
    exit('Database FILES MISSING:(');
    ?>
    <?php $_SESSION['main_title']  = "Registration Page"; ?>
    <?php
    if(isset($_SESSION['user_type'])){
      header('Location: index.php');
    }

    if(isset($_POST['submit']))
    {
      extract($_POST);

    // $name = $_POST["name"];
    // $email = $_POST["email"];
    // $password = $_POST["password"];

    // $name = mysqli_real_escape_string($con, $name);
    // $email = mysqli_real_escape_string($con, $email);
    // $password = mysqli_real_escape_string($con, $password);


          $created_at = date('Y-m-d');
          $queryInsert = "insert into user (name,last_name,user_name,user_type,email,password,created_at) values ('$name','$last_name','$user_name','$user_type','$email','$password','$created_at')";
          $resInsert = mysqli_query($con,$queryInsert);
            if($resInsert){

                $_SESSION['main_notice'] = "Successfully registered, login here!";
                header('Location: index.php');

            }else{
                $_SESSION['main_notice'] = "Some error, try again";
                header('Location: '.$_SERVER['PHP_SELF']);
            }
          }

    ?>
    <?php 
    if(is_file('include/header.php'))
    include_once('include/header.php');
    ?>
    <?php
             // define variables and set to empty values
             $nameErr = $lnameErr = $userErr = "";
             $name = $lname = $user = "";

             if ($_SERVER["REQUEST_METHOD"] == "POST") {
               // validate first name
                if (empty($_POST["name"])) {
                   $nameErr = "first Name is required";
                }else {
                   $name = test_input($_POST["name"]);
                }
               // check if name only contains letters and whitespace
                      if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
                        $nameErr = "Only letters and white space allowed"; 
                      }

               // validate last name
               if (empty($_POST["lname"])) {
                   $lnameErr = "Last Name is required";
                }else {
                   $lname = test_input($_POST["lname"]);
                }
               // check if name only contains letters and whitespace
                      if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
                        $lnameErr = "Only letters and white space allowed"; 
                      }

               // validate user type
               if (empty($_POST["user_name"])) {
                   $userErr = "Last Name is required";
                }else {
                   $user = test_input($_POST["user_name"]);
                }
               // check if name only contains letters and whitespace
                      if (!preg_match("/^[a-zA-Z ]*$/",$user)) {
                        $userErr = "Only letters and white space allowed"; 
                      }

             }//end validate tag

        ?>

    <div>

      <form name="register" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" onsubmit="return check()">
      <table>
        <tr>
          <td>Name</td>
          <td><input type="text" name="name" value='<?php echo $name ?>'><span style='color: red'>* <?php echo $nameErr;?></span>
    </td>
        </tr>
        <tr>
          <td>Last Name</td>
          <td><input type="text" name="last_name" value='<?php echo $lname ?>'><span style='color: red'>* <?php echo $lnameErr;?></span></td>
        </tr>
        <tr>
          <td>User Name</td>
          <td><input type="text" name="user_name" value='<?php echo $user ?>'><span style='color: red'>* <?php echo $userErr;?></span></td>
        </tr>
        <tr>
          <td>User Type</td>
          <td>
          <select name="user_type" >
            <option value="member">Member</option>
            <option value="leader">Leader</option>
          </select>
          </td>
        </tr>

        <tr>
          <td>Email</td>
          <td><input type="email" name="email" ></td>
        </tr>
        <tr>
          <td>Password:</td>
          <td><input type="password" name="password" id="password" ></td>
        </tr>
        <tr>
          <td>Confirm Password:</td>
          <td><input type="password" name="confirm_password" id="confirm_password" ></td>
        </tr>
        <tr>
          <td></td>
          <td><input type="submit" name="submit" value="Register"></td>
        </tr>
      </table>
      </form>   
    </div>
    <script>

             function test_input($data) {
                $data = trim($data);
                $data = stripslashes($data);
                $data = htmlspecialchars($data);
                return $data;
             }
    // function check(){
    //  if(document.getElementById('password').value != document.getElementById('confirm_password').value ){
    //      alert('password not match');
    //      return false;
    //  }else{
    //      return true;
    //  }
    // }
    </script> 
    <?php
    if(is_file('include/footer.php'))
    include_once('include/footer.php');
    ?>

我不确定是否遗漏了什么,但是当我在没有任何输入的情况下发送表单时,它会在数据库上处理它。如果我将输入放在名称字段中,它只是刷新并变为空白,即使值数据也不起作用。

我希望已经提供了足够的信息以供您帮助,如果有任何问题请问我。

提前致谢

1 个答案:

答案 0 :(得分:0)

您的代码的顺序似乎可能成为问题。您正在检查是否已设置$_POST['submit'],然后在执行验证的代码部分之前执行数据库操作。将值设置为空的部分应该首先出现,您要检查是否设置了$_POST['submit'],如果是,那么在if语句中进行验证。如此快速的伪代码:

include PHP files
check if user is already logged in
initialise variables
if submit is set {
    Validate the input
    if valid {
        Submit to database
    } else {
        return error messages as needed
    }
}

我希望这会有所帮助

编辑:

$stmt = $con->prepare("INSERT INTO user (name, last_name, user_name, user_type, email, password, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssss", $name, $last_name, $user_name, $user_type, $email, $password, $created_at);
$stmt->execute();
$stmt->close();
$con->close();

另外,注意到您的其他代码可能会出现一些问题。

  1. 在输入检查中,如果字段无效,则设置$nameErr之类的变量。一旦你对代码顺序进行了排序,你可能会发现你必须在验证结束时检查你是否真的有错误,否则它会尝试执行数据库部分。
  2. 错误变量被回显到页面但是如果所有输入都是可接受的,那么这些变量都不会定义,PHP可能会抛出错误
  3. 重新组织代码,然后仔细查看它,并考虑在提供有效和无效(或空)输入时数据流如何工作。