Search code examples
phpmysqlmysqliunique-index

I'm trying to do Signup and Login with PHP and MySQL


I'm trying to do Signup and Login with PHP and MySQL.. but when I enter the same email it shows me error... When I try to enter the same email.. already registered, it shows me an error. It should redirect straight to signup-success.html, but instead it shows an error on line 45.. i tried replacing it with but even this didn't help.. I'm new to php so I'm following the tutorial I'm using to do this... https://www.youtube.com/watch?v=5L9UhOnuos0

{
    $stmt->execute();
} catch (mysqli_sql_exception $e) {
    if ($e->getCode() == 1062) {
        die("email address is already taken");
    }
}

--------------------------------------------------------------------------
$password_hash = password_hash($_POST["password"], PASSWORD_DEFAULT);

$mysqli = require __DIR__ . "/database.php";

$sql = "INSERT INTO user (name, email, password_hash)
        VALUES (?, ?, ?)";
        
$stmt = $mysqli->stmt_init();

if ( ! $stmt->prepare($sql)) {
    die("SQL error: " . $mysqli->error);
}

$stmt->bind_param("sss",
                  $_POST["name"],
                  $_POST["email"],
                  $password_hash);
                  
if ($stmt->execute()) {

    header("Location: signup-success.html");
    exit;
    
} else {
    
    if ($mysqli->errno === 1062) {
        die("email already taken");
    } else {
        die($mysqli->error . " " . $mysqli->errno);
    }
}     

This is what website shows..

Fatal error: Uncaught mysqli_sql_exception: Duplicate entry '[email protected]' for key 'email' in D:\Programy\XAMPP\XAMPP\htdocs\login01\process-signup.php:45 Stack trace: #0 D:\Programy\XAMPP\XAMPP\htdocs\login01\process-signup.php(45): mysqli_stmt->execute() #1 {main} thrown in D:\Programy\XAMPP\XAMPP\htdocs\login01\process-signup.php on line 45


Solution

  • Your call to ->execute() is throwing an exception when you attempt to do your INSERT and it fails due to a duplicate value. (The rules about exception throwing changed in php version 8.) Exceptions are a bit of a pain in php; it's tricky to catch them and handle them completely without logging them.

    Here's what to do about that.

    1. Change your query to say INSERT IGNORE.

       $sql = "INSERT IGNORE INTO user (name, email, password_hash)
           VALUES (?, ?, ?)";
      
    2. Check whether the insert succeeded using affected_rows with code like this:

      $result = $stmt->execute();
      if ($result && $mysqli->affected_rows === 1) {
          header("Location: signup-success.html");
          exit;
      } else if ($result && $mysqli->affected_rows !== 1)
           die("email already taken");
      } else {
           die($mysqli->error . " " . $mysqli->errno);
      }
      

    This will let you control your logic without relying on error numbers except for when your SQL statement crashes and burns, not when you get a UNIQUE INDEX collision.