繁体   English   中英

表单未将用户输入提交到数据库 - PHP HTML

[英]Form not submitting user input to database - PHP HTML

我有一个使用 html 和 php 设置的简单表单,我希望将用户在注册时的输入保存到名为student数据库表中,并具有以下属性: firstNamelastNameusernameemailpswrd

填写完 html 表单后,我似乎在 URL 中收到错误: http://localhost:8888/PRCO304/signup.php?error=emptyfields&uname=kakakakakak&mail=kay@kay.com

请有人看看我到底做错了什么。 什么都没有插入数据库?

脚本/注册脚本.php:

<?php
// Checking whether the user got to this page by clicking the proper signup button.
if (isset($_POST['signup-submit'])) {

  // We include the connection script so we can use it later.
  // We don't have to close the MySQLi connection since it is done automatically, but it is a good habit to do so anyways since this will immediately return resources to PHP and MySQL, which can improve performance.
  require 'db.php';

  $firstName = $_POST['first-name'];
  $lastName = $_POST['last-name'];
  $username = $_POST['username'];
  $email = $_POST['email'];
  $password = $_POST['pwd'];
  $passwordRepeat = $_POST['pwd-repeat'];


  if (empty($firstName) || empty($lastName) || empty($username) || empty($email) || empty($password) || empty($passwordRepeat)) {
    header("Location: ../signup.php?error=emptyfields&uname=".$username."&mail=".$email);
    exit();
  }
  // Check for an invalid username AND invalid e-mail.
  else if (!preg_match("/^[a-zA-Z0-9]*$/", $username) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    header("Location: ../signup.php?error=invalidunamemail");
    exit();
  }
  // We check for an invalid username. In this case ONLY letters and numbers.
  else if (!preg_match("/^[a-zA-Z0-9]*$/", $username)) {
    header("Location: ../signup.php?error=invaliduname&mail=".$email);
    exit();
  }
  // We check for an invalid e-mail.
  else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    header("Location: ../signup.php?error=invalidmail&uname=".$username);
    exit();
  }
  // We check if the repeated password is NOT the same.
  else if ($password !== $passwordRepeat) {
    header("Location: ../signup.php?error=passwordcheck&uname=".$username."&mail=".$email);
    exit();
  }
  else {


    // First we create the statement that searches our database table to check for any identical usernames.
    $sql = "SELECT username FROM student WHERE username = ?;";
    // We create a prepared statement.
    $stmt = mysqli_stmt_init($conn);
    // Then we prepare our SQL statement AND check if there are any errors with it.
    if (!mysqli_stmt_prepare($stmt, $sql)) {
      // If there is an error we send the user back to the signup page.
      header("Location: ../signup.php?error=sqlerror");
      exit();
    }
    else {
      // Next we need to bind the type of parameters we expect to pass into the statement, and bind the data from the user.
      // In case you need to know, "s" means "string", "i" means "integer", "b" means "blob", "d" means "double".
      mysqli_stmt_bind_param($stmt, "s", $username);
      // Then we execute the prepared statement and send it to the database!
      mysqli_stmt_execute($stmt);
      // Then we store the result from the statement.
      mysqli_stmt_store_result($stmt);
      // Then we get the number of result we received from our statement. This tells us whether the username already exists or not!
      $resultCount = mysqli_stmt_num_rows($stmt);
      // Then we close the prepared statement!
      mysqli_stmt_close($stmt);
      // Here we check if the username exists.
      if ($resultCount > 0) {
        header("Location: ../signup.php?error=usertaken&mail=".$email);
        exit();
      }
      else {
        // If we got to this point, it means the user didn't make an error! :)

        // Next thing we do is to prepare the SQL statement that will insert the users info into the database. We HAVE to do this using prepared statements to make this process more secure. DON'T JUST SEND THE RAW DATA FROM THE USER DIRECTLY INTO THE DATABASE!

        // Prepared statements works by us sending SQL to the database first, and then later we fill in the placeholders (this is a placeholder -> ?) by sending the users data.
        $sql = "INSERT INTO student (firstName, lastName, username, email, pswrd) VALUES (?, ?, ?, ?, ?);";
        // Here we initialize a new statement using the connection from the db.php file.
        $stmt = mysqli_stmt_init($conn);
        // Then we prepare our SQL statement AND check if there are any errors with it.
        if (!mysqli_stmt_prepare($stmt, $sql)) {
          // If there is an error we send the user back to the signup page.
          header("Location: ../signup.php?error=sqlerror");
          exit();
        }
        else {


          $hashedPwd = password_hash($password, PASSWORD_DEFAULT);
          mysqli_stmt_bind_param($stmt, "sssss", $firstName, $lastName, $username, $email, $hashedPwd);
          // Then we execute the prepared statement and send it to the database!
          // This means the user is now registered! :)
          mysqli_stmt_execute($stmt);
          // Lastly we send the user back to the signup page with a success message!
          header("Location: ../signup.php?signup=success");
          exit();

        }
      }
    }
  }
  // Then we close the prepared statement and the database connection!
  mysqli_stmt_close($stmt);
  mysqli_close($conn);
}
else {
  // If the user tries to access this page an inproper way, we send them back to the signup page.
  header("Location: ../signup.php");
  exit();
}

注册.php:

<?php

// Here we create an error messages if the user made an error trying to sign up.
if (isset($_GET["error"])) {
if ($_GET["error"] == "emptyfields") {
    echo '<p class="signuperror">Fill in all fields!</p>';
}
else if ($_GET["error"] == "invalidunamedmail") {
    echo '<p class="signuperror">Invalid username and email!</p>';
}
else if ($_GET["error"] == "invaliduname") {
    echo '<p class="signuperror">Invalid username!</p>';
}
else if ($_GET["error"] == "invalidmail") {
    echo '<p class="signuperror">Invalid email!</p>';
}
else if ($_GET["error"] == "passwordcheck") {
    echo '<p class="signuperror">Your passwords do not match!</p>';
}
else if ($_GET["error"] == "usertaken") {
    echo '<p class="signuperror">Username is already taken!</p>';
}
}
// Here we create a success message if the new user was created.
else if (isset($_GET["signup"])) {
if ($_GET["signup"] == "success") {
    echo '<p class="signupsuccess">Signup successful!</p>';
}
}
?>
                    <form action="scripts/signup-script.php" method="post">

                        <div class="signupContainer">
                            <h1>Sign Up</h1>
                            <p>Please fill in this form to create an account.</p>
                            <hr>
                        <?php
                            if (!empty($_GET["first-name"])) {
                                echo '<label for="first-name"><b>First Name</b></label>
                                <input type="text" placeholder="First Name" name="first-name" value="'.$_GET["first-name"].'">';
                            } else {
                                echo '<label for="first-name"><b>First Name</b></label>
                                <input type="text" placeholder="First Name" name="first-name">';
                            }
                            if (!empty($_GET["last-name"])) {
                                echo '<label for="last-name"><b>Last Name</b></label>
                                <input type="text" placeholder="Last Name" name="last-name" value="'.$_GET["last-name"].'">';
                            } else {
                                echo '<label for="last-name"><b>Last Name</b></label>
                                <input type="text" placeholder="Please Enter Last Name" name="last-name">';
                            }
                            if (!empty($_GET["username"])) {
                                echo '<label for="username"><b>Username</b></label>
                                <input type="text" placeholder="Username" name="username" value="'.$_GET["username"].'">';
                            } else{
                                echo '<label for="username"><b>Username</b></label>
                                <input type="text" placeholder="Username" name="username">';
                            }
                            if (!empty($_GET["email"])) {
                                echo '<label for="email"><b>Email</b></label>
                                <input type="text" placeholder="Email" name="email" value="'.$_GET["email"].'">';
                            } else {
                                echo '<label for="email"><b>Email</b></label>
                                <input type="text" placeholder="Email" name="email">';
                            }
                        ?>
                            <label for="psw"><b>Password</b></label>
                            <input type="password" placeholder="Password" name="psw">

                            <label for="psw-repeat"><b>Repeat Password</b></label>
                            <input type="password" placeholder="Repeat Password" name="psw-repeat">

                            <label>
                            <input type="checkbox" checked="checked" name="remember"> Remember me
                            </label>

                            <p>By creating an account you agree to our <a href="#">Terms & Privacy</a>.</p>

                            <div class="clearfix">
                            <button type="submit" class="signupBtn" name="signup-submit">Sign Up</button>
                            </div>
                        </div>
                    </form>

问题是你的表单有name="psw"name="psw-repeat"而你的脚本寻找$_POST['pwd']; $_POST['pwd-repeat']; psw VS pwd


在此期间,我们可以稍微简化一下脚本:

脚本/注册脚本.php:

<?php
// Checking whether the user got to this page by clicking the proper signup button.

if (!isset($_POST['signup-submit'])) {
    // If the user tries to access this page an inproper way, we send them back to the signup page.
    header('Location: ../signup.php');
    exit();
}


// We include the connection script so we can use it later.
// We don't have to close the MySQLi connection since it is done automatically,
// but it is a good habit to do so anyways since this will immediately return
// resources to PHP and MySQL, which can improve performance.
require 'db.php';
$firstName      = !empty($_POST['first-name']) ? $_POST['first-name'] :'';
$lastName       = !empty($_POST['last-name'])  ? $_POST['last-name'] : '';
$username       = !empty($_POST['username'])   ? $_POST['username'] : '';
$email          = !empty($_POST['email'])      ? $_POST['email'] : '';
$password       = !empty($_POST['pwd'])        ? $_POST['pwd'] : '';
$passwordRepeat = !empty($_POST['pwd-repeat']) ? $_POST['pwd-repeat'] : '';
$location       = null;

switch (true) {
    case !$firstName || !$lastName || !$username || !$email || !$password || !$passwordRepeat:
        $location = "Location: ../signup.php?error=emptyfields&uname=$username&mail=$email";
        break;
    case !preg_match('/^[a-zA-Z0-9]*$/', $username) && !filter_var($email, FILTER_VALIDATE_EMAIL):
        // Check for an invalid username AND invalid e-mail.
        $location = 'Location: ../signup.php?error=invalidunamemail';
        break;
    case !preg_match('/^[a-zA-Z0-9]*$/', $username):
        // We check for an invalid username. In this case ONLY letters and numbers.
        $location = "Location: ../signup.php?error=invaliduname&mail=$email";
        break;
    case !filter_var($email, FILTER_VALIDATE_EMAIL):
        // We check for an invalid e-mail.
        $location = "Location: ../signup.php?error=invalidmail&uname=$username";
        break;
    case $password !== $passwordRepeat:
        // We check if the repeated password is NOT the same.
        $location = "Location: ../signup.php?error=passwordcheck&uname=$username&mail=$email";
        break;
}
// if we had errors, stop here
if ($location) {
    header($location);
    exit();
}


// First we create the statement that searches our database table to check for any identical usernames.
$sql = "SELECT username FROM student WHERE username = ?;";
// We create a prepared statement.
$stmt = mysqli_stmt_init($conn);
// Then we prepare our SQL statement AND check if there are any errors with it.
if (!mysqli_stmt_prepare($stmt, $sql)) {
    // If there is an error we send the user back to the signup page.
    header("Location: ../signup.php?error=sqlerror");
    exit();
}

// Next we need to bind the type of parameters we expect to pass into the statement, and bind the data from the user.
// In case you need to know, "s" means "string", "i" means "integer", "b" means "blob", "d" means "double".
mysqli_stmt_bind_param($stmt, "s", $username);
// Then we execute the prepared statement and send it to the database!
mysqli_stmt_execute($stmt);
// Then we store the result from the statement.
mysqli_stmt_store_result($stmt);
// Then we get the number of result we received from our statement. This tells us whether the username already exists or not!
$resultCount = mysqli_stmt_num_rows($stmt);
// Then we close the prepared statement!
mysqli_stmt_close($stmt);
// Here we check if the username exists.
if ($resultCount > 0) {
    header("Location: ../signup.php?error=usertaken&mail=".$email);
    exit();
}

// If we got to this point, it means the user didn't make an error! :)

// Next thing we do is to prepare the SQL statement that will insert the users info into the database. We HAVE to do this using prepared statements to make this process more secure. DON'T JUST SEND THE RAW DATA FROM THE USER DIRECTLY INTO THE DATABASE!

// Prepared statements works by us sending SQL to the database first, and then later we fill in the placeholders (this is a placeholder -> ?) by sending the users data.
$sql = "INSERT INTO student (firstName, lastName, username, email, pswrd) VALUES (?, ?, ?, ?, ?);";
// Here we initialize a new statement using the connection from the db.php file.
$stmt = mysqli_stmt_init($conn);
// Then we prepare our SQL statement AND check if there are any errors with it.
if (!mysqli_stmt_prepare($stmt, $sql)) {
    // If there is an error we send the user back to the signup page.
    $error = mysqli_stmt_error($stmt);
    header("Location: ../signup.php?error=sqlerror&description=$error");
    exit();
}


$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "sssss", $firstName, $lastName, $username, $email, $hashedPwd);
// Then we execute the prepared statement and send it to the database!
// This means the user is now registered! :)
mysqli_stmt_execute($stmt);
// Lastly we send the user back to the signup page with a success message!
header("Location: ../signup.php?signup=success");

// Then we close the prepared statement and the database connection!
mysqli_stmt_close($stmt);
mysqli_close($conn);

exit();

注册.php:

<?php

$statusMessage = '';
if (isset($_GET['error'])) {
// Here we create an error messages if the user made an error trying to sign up.
    $errorMap = [
        'emptyfields'       => 'Fill in all fields!',
        'invalidunamedmail' => 'Invalid username and email!',
        'invaliduname'      => 'Invalid username!',
        'invalidmail'       => 'Invalid email!',
        'passwordcheck'     => 'Your passwords do not match!',
        'usertaken'         => 'Username is already taken!',
    ];
    $message       = $errorMap[$_GET['error']] ?: 'An unknown error occurred';
    $statusMessage = "<p class='signuperror'>$message</p>";
}
else if (isset($_GET['signup']) && $_GET['signup'] === 'success') {
// Here we create a success message if the new user was created.
    $statusMessage = '<p class="signupsuccess">Signup successful!</p>';
}

$firstName      = !empty($_GET['first-name']) ? $_GET['first-name'] :'';
$lastName       = !empty($_GET['last-name'])  ? $_GET['last-name'] : '';
$username       = !empty($_GET['username'])   ? $_GET['username'] : '';
$email          = !empty($_GET['email'])      ? $_GET['email'] : '';
$password       = !empty($_GET['pwd'])        ? $_GET['pwd'] : '';
$passwordRepeat = !empty($_GET['pwd-repeat']) ? $_GET['pwd-repeat'] : '';

?>
<?= $statusMessage ?>
<form action="scripts/signup-script.php" method="post">
    <div class="signupContainer">
        <h1>Sign Up</h1>
        <p>Please fill in this form to create an account.</p>
        <hr>
        <label for="first-name"><b>First Name</b></label>
        <input type="text" placeholder="First Name" name="first-name" value="<?= $firstName ?>">
        <label for="last-name"><b>Last Name</b></label>
        <input type="text" placeholder="Last Name" name="last-name" value="<?= $lastName ?>">
        <label for="username"><b>Username</b></label>
        <input type="text" placeholder="Username" name="username" value="<?= $username ?>">
        <label for="email"><b>Email</b></label>
        <input type="text" placeholder="Email" name="email" value="<?= $email ?>">
        <label for="psw"><b>Password</b></label>
        <input type="password" placeholder="Password" name="pwd">
        <label for="psw-repeat"><b>Repeat Password</b></label>
        <input type="password" placeholder="Repeat Password" name="pwd-repeat">
        <label>
            <input type="checkbox" checked="checked" name="remember"> Remember me
        </label>
        <p>By creating an account you agree to our <a href="#">Terms & Privacy</a>.</p>
        <div class="clearfix">
            <button type="submit" class="signupBtn" name="signup-submit">Sign Up</button>
        </div>
    </div>
</form>

暂无
暂无

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

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