-1

Trying to create a basic SQL signup php script. I am allowed to sign up and it redirects me to the login page, but duplicate emails gives an error at the if statement and ignores the else.

The error I'm getting:

Fatal error: Uncaught mysqli_sql_exception: Duplicate entry 'test@example.com' for key 'email' in C:\xampp\htdocs\websiteproject\html\php\signup.php:20 Stack trace: #0 C:\xampp\htdocs\websiteproject\html\php\signup.php(20): mysqli_stmt->execute() #1 {main} thrown in C:\xampp\htdocs\websiteproject\html\php\signup.php on line 20

My code:

<?php
$password_hash = password_hash($_POST["password"], PASSWORD_DEFAULT);
$mysqli = require __DIR__ . "/database.php";
$sql = "INSERT INTO siteusers (username, email, pass_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: ../loginRegister.php");
} else{
    die($mysqli->error . "" . $mysqli->$errno);
}

Any clue why it errors at the if statement and not the else? Thanks.

Dharman
  • 30,962
  • 25
  • 85
  • 135
APP
  • 3
  • 1

1 Answers1

-1

A try/catch would be more appropriate here. An error thrown by MySql will break the script where it occurs, not return a falsy value as you seem to expect.

try {
  $stmt->execute();
  header("Location: ../loginRegister.php");
} catch (Exception $e) {
  die($mysqli->error . "" . $mysqli->$errno);
}

Alternatively, you could validate the incoming request data and check first that the email is not already in use.

msmahon
  • 453
  • 2
  • 11