Help with an error in my signup form?

This is my signup.inc.php

// isset gör att man endast kan hämta info genom knappen signup annars så kommer error meddelande
if (isset($_POST['signup-submit'])){

    require 'dbh.inc.php';

    $username  = $_POST['uid'];
    $email  = $_POST['mail'];
    $password  = $_POST['pwd'];
    $passwordRepeat  = $_POST['pwd-repeat'];
// om username, email, password eller passwordrepeat inte är ifyllt så kommer error
    if (empty($username) || empty($email) || empty($password) || empty($passwordRepeat)){
        header("Location: ../signup.php?error=emptyfields&uid=".$username. "&mail=".$email);
        exit();
    }
// checkar om mail o username är rätt, om man inte fyllt i rätt mail eller username så får man ingenting skickat tillbaka
    else if (!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/", $username)){
        header("Location: ../signup.php?error=invalidmail&uid");
        exit();
    }
// kollar om mail är rätt och skickar tillbaka username när man blir tillbakaskickad
    else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
        header("Location: ../signup.php?error=invaliduid&mail". $username);
        exit();
    }
// kollar om användarnamn är rätt, får bara vara tecken inom ramen a-zA-Z0-9, skickar tillbaka mail.
    else if(!preg_match("/^[a-zA-Z0-9]*$/", $username)){
        header("Location: ../signup.php?error=invaliduid&mail". $email);
        exit();
    }
// kollar om lösenordet matchar repeterade lösenordet, skickar tillbaka mail och username
    else if($password !== $passwordRepeat){
        header("Location: ../signup.php?error=passwordcheckuid".$username. "&mail=". $email);
        exit();
    }
//  kollar om användarnamet finns i databasen, om det finns kommer error. ? frågetecknet i slutet på första raden användes som placeholder itsället för att folk ska kunna skriva sql kod i username field och förstöra databasen.
    else{
        $sql = "SELECT uidUsers FROM users WHERE uidUsers=?";
        $stmt = mysqli_stmt_init($conn);
    if (!mysqli_stmt_prepare($stmt, $sql)){
        header("Location: ../signup.php?error=sqlerror");
        exit();
    }
// detta gör att informationen skickas till databasen för att kunna kolla om det matchar
    else{
        mysqli_stmt_bind_param($stmt, "s", $username);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_store_result($stmt);
        $resultCheck = mysqli_stmt_num_rows($stmt);
    if ($resultCheck > 0){
        header("Location: ../signup.php?error=usertaken&mail=".$email);
        exit();
        }
    else {
        $sql = "INSERT INTO users (uidUsers, emailUsers, pwdUsers) VALUES (?, ?, ?)";
        $stmt = mysqli_stmt_init($conn);
    if (!mysqli_stmt_prepare($stmt, $sql)){
        header("Location: ../signup.php?error=sqlerror");
        exit();    
        }
    else {
        $hashedPwd = password_hasg($password, PASSWORD_DEFAULT);

        mysqli_stmt_bind_param($stmt, "sss", $username, $email, $hashedPwd);
        mysqli_stmt_execute($stmt);
        header("Location: ../signup.php?signup=success");
        exit();
    }
    }
    }
    }
    mysqli_stmt_close($stmt);
    mysqli_close($conn);

}
else {
    header("Location: ../signup.php");
    exit();
}

This is my dbh.inc.php

//om man jobbar i ex vis wordpress så ska detta vara en databas i wordpress

$servername = "localhost";

$dBUsername = "root";

$dBPassword = "";

$dBName = "loginsystem";

$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);

if (!$conn){

die("Connection failed:".mysqli_connect_error());

}

I get the sqlerror, but i cant find the problem.

Please put it in a format so that anyone reading this can understand it. SO kindly use the code sign which you can see while you writing down your code. Or you can go through the instructions and then paste. First clear this mess and then we can help you.

watch now, ! removed the php and now you can read this…
Sorry I didn’t se that it was unreadable

And what error is it giving back?

I get an =sqlerror in the URL

Print the actual errors out, since the errors you have for what happens don’t help you at all figure out what isn’t working properly.

But this isn’t how you do a prepared statement.

This style of coding is showing up recently. I wonder where it is being taught at?

You have a wall of unnecessary code, that’s also missing some useful features. By putting the form and form processing code on separate pages, you are doubling the amount of code needed to display helpful user error messages (assuming you are actually taking the values from the url and displaying messages and using the & in the values is breaking the url) and filling up the page with redirect statements. You are also creating all possible combinations of email/username validation.

One point of programming is to produce working code without spending your life typing on a keyboard. You should use the least amount of code that accomplishes a task, not the most.

If you do the following, you will end up with the simplest code, that will either work or it (and php/MySql) will tell you whey it isn’t working -

  1. Put the form processing code and the form on the same page. This will eliminate all the redirecting, allow you to validate all the inputs at once, without forming combinations, without all the else if() statements, and let you set up and display unique and helpful user error messages.
  2. Use an array to hold user error messages. This array is also an error flag. If the array is empty, there are no errors. If the array is not empty, there are errors.
  3. Use exceptions to handle database errors (connection, query, prepare, and execute) and in most cases let php catch and handle the exception where it will use its error related settings to control what happens with the actual error information (database errors will get displayed or logged the same as php errors.) The exception to this rule is when inserting/updating duplicate user submitted data. This is a ‘recoverable’ application error that the user can correct. In this case, your code would catch the exception, detect if a duplicate key error occurred, and set up a user message telling the user what value was duplicate.
  4. Don’t write out line after line of code that copies variables to other variables for no reason. This is just a waste of your time. You should trim() all submitted form data, mainly so that you can detect if all white-space characters where entered. This can be done with ONE line of code, by operating on the data as a set, as an array. If I/others have time, they will post an example.
  5. Don’t SELECT data in order to decide if you should INSERT it. In fact, there’s a race condition doing it this way where concurrent instances of your code (think of duplicate form submissions, the rare instance of concurrent visitors wanting the same username, or hackers trying to trigger errors) will all find that the value doesn’t exist from the SELECT query and try to insert it. Instead, define the column(s) in your database table as unique indexes, just INSERT the data, and detect if a duplicate key error occurred (see item #3 in this list.)
  6. If you are using the the mysqli extension, just use the mysqli_prepare() statement. Several people have been using the mysqli_stmt_init/mysqli_stmt_prepare combination. Why use two statements when one will do?
  7. The execute() statement can fail too, but you don’t have any error handling for them. Rather than to add more logic to your code, use exceptions to handle database statement errors (see item #3 in this list.) Since program execution transfers to the exception handler upon an error, your main code only ‘sees’ error free execution.
  8. Php closes database connections when the script ends, so you don’t have to.
  9. Lastly, you need to switch to the php PDO extension. The PDO extension is simpler (it takes less lines of code to accomplish a task), and is more consistent (the result of prepared and non-prepared queries can be treated the same) than the mysqli extension.

Edit: also, both the username and email address must be unique in the table.

1 Like

Hi @vukle
the only problem I see in this code is:

$hashedPwd = password_hasg($password, PASSWORD_DEFAULT);

The function is password_hash.

So check in the database if you have the table users and if you have the 3 columns: uidUsers, emailUsers, pwdUsers.

Or maybe the table has some extra columns without default values.

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service