所以我有注册功能:
<?php
function sign_up($login, $password, $email){
global $db;
if(is_login_exist($login)){
return ['error' => 'Login already exists', 'result' => null];
}
if(is_email_exist($email)){
return ['error' => 'Email already exists', 'result' => null];
}
//hash password
$password = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
$stmt = $db->prepare("INSERT INTO users (login, password, email) VALUES (?, ?, ?)");
//add check
$stmt->bind_param("sss", $login, $password, $email);
$stmt->execute();
$stmt->close();
return ['error' => null, 'result' => 'success'];
}?>
因此,如果我在登录已经存在时遇到例如错误,我会返回关联数组 ['error' => '登录名已经存在', 'result' => null]
问题:将"result"参数返回为空还是假是否正确?
我会返回: status => 'ok'/'error'
和可选的'error_message' => 'message'
,并在状态为错误时'error_code' => 0
。但这只是我的意见。
如果有问题,我会抛出一个异常。
function sign_up(mysqli $db, $login, $password, $email){
// hash password
$password = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
// try to insert
$stmt = $db->prepare("INSERT INTO users (login, password, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $login, $password, $email);
$stmt->execute();
return true;
}
要求:
- Mysqli 设置为在出现错误时抛出异常 =>
mysqli_report()
login
和email
字段存在UNIQUE
约束