0

This is my HTML file:

 <div class="form">
            <form action="register.php" method="POST" class="register-form">
            <input type="text" placeholder="Username" name="username" required/>
            <input type="password" placeholder="Password" name="password" required/>
            <input type="text" placeholder="Email" name="email"  required/>
            <button type="submit">Create</button>
            <p class="message"> Already Registered? <a href="#">Login</a>
            </p>
            </form>
    
            <form action="login.php" method="POST" class="login-form">
            <input type="text" placeholder="Username" name="username" required/>
            <input type="password" placeholder="Password" name="password" required/>
            <button type="submit">login</button>
            <p class="message">Not Registered? <a href="#">Register</a></p>
            </form>

This is my PHP file:

$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];

if (!empty($username) || !empty($password) || !empty($email)) {
 $serverName = "localhost";
    $dbUsername = "root";
    $dbPassword = "";
    $dbname = "account";

    //create connection
    $conn = new MySQLI($serverName,$dbUsername,$dbPassword,$dbname);
    if (mysqli_connect_error()) {
     die('Connect Error('. mysqli_connect_errno().')'. mysqli_connect_error());
    } else {
     $SELECT = "SELECT email From users Where email = ? Limit 1";
     $INSERT = "INSERT Into users (username, password, email) values(?, ?, ?)";

     //Prepare statement
     $stmt = $conn->prepare($SELECT);
     $stmt->bind_param("s", $email);
     $stmt->execute();
     $stmt->bind_result($email);
     $stmt->store_result();
     $stmt->store_result();
     $stmt->fetch();
     $rnum = $stmt->num_rows;
     if ($rnum==0) {
      $stmt->close();
      $stmt = $conn->prepare($INSERT);
      $stmt->bind_param("sss", $username, $password, $email);
      $stmt->execute();
      echo "New record inserted sucessfully";
     } else {
      echo "Someone already register using this email";
     }
     $stmt->close();
     $conn->close();
    }
} else {
 echo "All field are required";
 die();
}

I have a database called account, with a table called users, columns called id, email, username & password. The ID is an INT, and selected as primary. And the rest is set as VARCHAR.

When I enter some names in the form, and press signup, it's giving me the result "New record inserted successfully", so I have no idea, why this doesn't work.

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • The [docs](https://www.php.net/manual/en/mysqli-stmt.execute.php) for statement execution say that the function `Returns TRUE on success or FALSE on failure.` and you never check this, so you can't really be sure there were no errors, you only assume everything went right. – El_Vanja Nov 10 '20 at 12:17
  • @El_Vanja You should never check for the return value. – Dharman Nov 10 '20 at 12:30
  • 4
    **Never store passwords in clear text or using MD5/SHA1!** Only store password hashes created using PHP's [`password_hash()`](https://php.net/manual/en/function.password-hash.php), which you can then verify using [`password_verify()`](https://php.net/manual/en/function.password-verify.php). Take a look at this post: [How to use password_hash](https://stackoverflow.com/q/30279321/1839439) and learn more about [bcrypt & password hashing in PHP](https://stackoverflow.com/a/6337021/1839439) – Dharman Nov 10 '20 at 12:32
  • Please, enable error reporting [How to get the error message in MySQLi?](https://stackoverflow.com/a/22662582/1839439) – Dharman Nov 10 '20 at 12:32
  • @Dharman If i understand your question correctly, my VARCHAR field is set to 255. – Jonas Schou Nov 10 '20 at 12:39
  • @Dharman So i have now enabled the Error reporting before the connection: mysqli_report(MYSQLI_REPORT_ERROR); And now i got this: Warning: mysqli_stmt::execute(): (23000/1048): Column 'email' cannot be null in C:\xampp\htdocs\register.php on line 35 New record inserted sucessfully – Jonas Schou Nov 10 '20 at 12:44
  • Also, this condition is wrong: `if (!empty($username) || !empty($password) || !empty($email))` if what you want really is `"All field are required"`. Currently, you're saying "perform this action if any of these parameters is set". You should either remove the negations or convert OR operators to AND. – El_Vanja Nov 10 '20 at 12:50
  • I have now added the STRICT, and selected this if i understand correct? https://gyazo.com/9560266b60835e3b0b638ebbd61e8776 Im sorry it is in danish, but i don't know how to change the language. – Jonas Schou Nov 10 '20 at 12:51
  • @El_Vanja Thanks for trying to help me, im currently completely new to coding in PHP, so could you maybe give me some more explanation of what i should do ? – Jonas Schou Nov 10 '20 at 12:52
  • So i replace this line if (!empty($username) || !empty($password) || !empty($email)) with if ($username && $password && $email ? – Jonas Schou Nov 10 '20 at 12:54
  • If you are new to PHP, then please don't learn mysqli. It is not suitable for beginners. Learn PDO instead. See https://phpdelusions.net/pdo – Dharman Nov 10 '20 at 12:55
  • I got this challenge from my Teacher, so i have to do it with MySQLI and PHP – Jonas Schou Nov 10 '20 at 12:56
  • Then tell your teacher they need to update their curriculum. mysqli is not for beginners and teaching this is only going to make students hate PHP – Dharman Nov 10 '20 at 12:57
  • Haha i will do. But is there any chance i could get this to work or ? – Jonas Schou Nov 10 '20 at 12:59
  • I have replaced the if (!empty($username) || !empty($password) || !empty($email)) with if ($username && $password && $email) But i still gives me this fatal error: Fatal error: Uncaught mysqli_sql_exception: Column 'email' cannot be null in C:\xampp\htdocs\register.php:35 Stack trace: #0 C:\xampp\htdocs\register.php(35): mysqli_stmt->execute() #1 {main} thrown in C:\xampp\htdocs\register.php on line 35 – Jonas Schou Nov 10 '20 at 13:07

1 Answers1

0

Your problem is the way you use mysqli. As I have said in the comments mysqli is not suitable for beginners, the API is very cumbersome.

Look at the lines before your INSERT statement. You perform a SELECT statement, presumably to check if the email has been used before and then you bind the result variable. The variable is called $email. You overwrite your user input with the result from SELECT. But this is not the right way.

The simple solution would be to name the variable something else, but the right answer is that you should fetch a count from the SQL not the value. See adjusted code below:

<?php

$username = filter_input(INPUT_POST, 'username');
$password = filter_input(INPUT_POST, 'password');
$email = filter_input(INPUT_POST, 'email');

if ($username && $password && $email) {
    $serverName = "localhost";
    $dbUsername = "root";
    $dbPassword = "";
    $dbname = "account";

    //create connection
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $conn = new MySQLI($serverName, $dbUsername, $dbPassword, $dbname);
    $conn->set_charset('utf8mb4'); // always set the charset

    //Prepare statement
    $stmt = $conn->prepare("SELECT COUNT(email) From users Where email = ? Limit 1");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($exists); // we fetch the count
    $stmt->fetch();
    if (!$exists) {
        $stmt = $conn->prepare("INSERT Into users (username, password, email) values(?, ?, ?)");
        // Don't forget to hash the password and never store the real password anywhere
        $hash = password_hash($password, PASSWORD_DEFAULT);
        $stmt->bind_param("sss", $username, $hash, $email);
        $stmt->execute();
        echo "New record inserted sucessfully";
    } else {
        echo "Someone already register using this email";
    }
} else {
    echo "All field are required";
}

I remove the unnecessary code and removed the store_result() and num_rows. They are not helpful in this situation. Instead fetch a count of matching rows and check if the count is not 0 with if(!$exists)

Dharman
  • 30,962
  • 25
  • 85
  • 135