Question

I've searched Google but not had much luck with this, so maybe SO can help. I am developing a user authentication system for a couple of projects and need to ensure that the email address, which is also the username, is unique.

I set the field as unique in the MySQL query, but I need a way to cancel an SQL query and notify the user that "the specified email is already in use" if the supplied email matches an existing record.

I could do a select query before the insert, but I am wondering if there is a way to write the SQL query so that an insert is performed IF NOT EXISTS existing@example.com IN email or something like that.

Then if the insert is not performed, I need to know, and I need to be able to tell it apart from another error.

Is this possible? How?

Was it helpful?

Solution

If you're using PDO, you can just catch the exception and check the status code, eg

// make sure you're set to throw exceptions
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $pdo->prepare('INSERT INTO `user` (`email`) VALUES (?)');
try {
    $stmt->execute([$email]);
} catch (PDOException $e) {
    $errorInfo = $stmt->errorInfo(); // apparently PDOException#getCode() is pretty useless
    if ($errorInfo[1] == 1586) {
        // inform user, throw a different exception, etc
    } else {
        throw $e; // a different error, let this exception carry on
    }        
}

See http://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html#error_er_dup_entry_with_key_name

The process would be similar if using MySQLi

$stmt = $mysqli->prepare('INSERT INTO `user` (`email`) VALUES (?)');
$stmt->bind_param('s', $email);
if (!$stmt->execute()) {
    if ($stmt->errno == 1586) {
        // inform user, throw a different exception, etc
    } else {
        throw new Exception($stmt->error, $stmt->errno);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top