0

I have a simple form set up using html and php, I want the user inputs on signup to be saved into my database table called student with the following attributes: firstName, lastName, username, email & pswrd.

After filling the html form out, I seem to be getting the error in the URL of: "http://localhost:8888/PRCO304/signup.php?error=emptyfields&uname=kakakakakak&[email protected]"

Please could someone take a look to see what on earth I'm doing wrong please. Nothing gets inserted into the DB?

scripts/signup-script.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();
}

signup.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>
1
  • what do you get if you do a var_dump($_POST) in scripts/signup-script.php ? Commented Feb 8, 2020 at 23:31

1 Answer 1

2

The issue is that your form has name="psw" and name="psw-repeat" while your script looks for $_POST['pwd']; and $_POST['pwd-repeat']; psw vs pwd


While we're at it, we could simplify the scripts a bit:

scripts/signup-script.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();

signup.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>
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you Wesley, I no longer get that error thanks to you, however now I seem to be hitting the /signup.php?error=sqlerror do you know what that could possibly be?
@K.Haydock try updating that error to this to see what the actual error is $error = mysqli_stmt_error($stmt); header("Location: ../signup.php?error=sqlerror&description=$error");
@K.Haydock Updated the answer above to show a few ways the scripts could be simplified a bit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.