首页 > 解决方案 > 当用户输入错误时 PHP 代码成功完成

问题描述

我正在编写的应用程序中的这段代码有问题:

<?php

session_start();

include('api/dbconnect.php');

$msg = "";

if(isset($_POST['register-submit'])) {
// Now we check if the data was submitted, isset() function will check if the data exists.
    if (!isset($_POST['first_name'], $_POST['last_name'], $_POST['email'], $_POST['username'], $_POST['password'])) {
        // Could not get the data that should have been sent.
        $msg = 'Please complete the registration form';
    }
// Make sure the submitted registration values are not empty.
    if (empty($_POST['first_name']) || 
        empty($_POST['last_name'])  || 
            /* empty($_POST['email']) || */ 
        empty($_POST['username']) || 
        empty($_POST['password'])) {
        
        // One or more values are empty.
        $msg = 'All fields are required for the form to be submitted';
    }

    /*if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        die ('The email address provided is invalid');
    }*/

    if (preg_match('/[A-Za-z0-9]+/', $_POST['username']) == 0) {
        $msg = 'The username provided is invalid';
    }

    if (strlen($_POST['password']) > 20 || strlen($_POST['password']) < 5) {
        $msg = 'Password must be between 5 and 20 characters';
    }

    if ($_POST['password'] != $_POST['confirm_pwd']) {
        $msg = 'The two password provided do not match.';
    }

    // We need to check if the account with that username exists.
    if ($stmt = $pdo->prepare('SELECT id, password FROM users WHERE username = ?')) {
        // Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
        $stmt->bindParam(1, $_POST['username']);
        $stmt->execute();
        // Store the result so we can check if the account exists in the database.
        if ($stmt->num_rows > 0) {
            // Username already exists
            $msg = 'Another account with this username already exists';
        } else {
            // Username doesn’t exist, insert new account
            if ($stmt = $pdo->prepare('INSERT INTO users (first_name, last_name, email, username, password) VALUES (?, ?, ?, ?, ?)')) {
                // We do not want to expose passwords in our database, so hash the password and use password_verify when a user logs in.
                $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
                $stmt->bindParam(1, $_POST['first_name']);
                $stmt->bindParam(2, $_POST['last_name']);
                $stmt->bindParam(3, $_POST['email']);
                $stmt->bindParam(4, $_POST['username']);
                $stmt->bindParam(5, $password);
                $stmt->execute();
                header('Location: users.php');
            } else {
                // Something is wrong with the SQL statement. Check to make sure the users table exists with all three fields.
                $msg = 'There was a problem creating this account. Contact your Network Administrator.';
            }
        }
        $stmt->close();
    }
    else {
        // Something is wrong with the SQL statement. Check to make sure the users table exists with all 3 fields.
        $msg = 'There was a problem creating this account. Contact your network administrator.';
    }
    //$con->close();
}

?>

此代码应该创建一个新用户并将其添加到 MySQL 表中。该代码正在运行,但即使它是故意的,该代码也不会产生错误。比如我输入了两个不同的密码,那么代码就认为没有问题,所以就成功完成了注册。到处都有一个$msg变量,代码需要停止并重新加载页面以在 HTML 表单中显示错误,以便用户可以更正它,但它不起作用。

我在代码中没有看到什么?

这是代码所属的 HTML 表单:

<form class="user" method="post" action="user_new.php">
  <div class="custom-control small">
    <strong class="text-danger"><?php echo $msg; ?></strong>
  </div>
  <div class="form-group row">
    <div class="col-sm-6 mb-3 mb-sm-0">
      <input type="text" class="form-control form-control-user" id="first_name" name="first_name" placeholder="First Name" autocomplete="off" required>
    </div>
    <div class="col-sm-6">
      <input type="text" class="form-control form-control-user" id="last_name" name="last_name" placeholder="Last Name" autocomplete="off" required>
    </div>
  </div>
  <div class="form-group row">
    <div class="col-sm-6 mb-3 mb-sm-0">
      <input type="email" class="form-control form-control-user" id="email" name="email" placeholder="Email Address (optional)" autocomplete="off">
    </div>
    <div class="col-sm-6">
      <input type="text" class="form-control form-control-user" id="username" name="username" placeholder="Username" autocomplete="off" required>
    </div>
  </div>
  <div class="form-group row">
    <div class="col-sm-6 mb-3 mb-sm-0">
      <input type="password" class="form-control form-control-user" id="password" name="password" placeholder="Password" autocomplete="off" required>
    </div>
    <div class="col-sm-6">
      <input type="password" class="form-control form-control-user" id="confirm_pwd" name="confirm_pwd" placeholder="Confirm Password" autocomplete="off" required>
    </div>
  </div>
  <button type="submit" name="register-submit" class="btn btn-primary btn-user btn-block" style="background-color: #a40000; border-color: #a40000;">Create User Account</button>
  <hr>
  <a href="users.php" class="btn btn-warning btn-user btn-block" style="background-color: #2658a8; border-color: #2658a8;">Return to Users</a>
</form>

标签: phpmysql

解决方案


您的代码有一些需要注意的地方。

关于第 1 点的旁注,请参阅下面的“附加说明”。

  1. $msg<你没有对那个变量做任何事情。它们只是变量声明。您可以在要回显该变量的页面上回显该变量并在其后添加exit;以使其停止执行。

  2. num_rows是一个 mysqli_ 函数。您不能将其与 PDO 混合使用。您可以使用rowCount()orfetchColumn()if ($stmt->rowCount() > 0){...} .

    或与fetchColumn()

     $if_row = $stmt->fetchColumn();
    
     if ($if_row > 0) {
         $msg = "A record exists.";
     }
    
  3. exit;在每个标题后添加一个。否则,您的代码可能希望继续走得更远。

    注意:由于您使用的是标头进行重定向,因此请确保您没有在标头之前输出,否则会失败。

补充说明:

使用if ($stmt = $pdo->prepare....){...}可能不是一个好主意,因为这可能会默默地过早地失败。我会“不”使它成为条件语句,然后检查是否存在一行并从那里处理错误。

另外,您<?php echo $msg; ?>的表单内部可能会抛出未定义的变量消息。您可以为其使用三元运算符或标准if/else.

例如:

<?php if(!empty($msg)) { echo $msg; } ?>

推荐阅读