Reject PDO MySQL statement if a specified value is found in a field?

橙三吉。 提交于 2019-12-23 05:14:00

问题


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?


回答1:


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);
    }
}


来源:https://stackoverflow.com/questions/21618194/reject-pdo-mysql-statement-if-a-specified-value-is-found-in-a-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!