【发布时间】:2021-11-25 14:43:12
【问题描述】:
我正在使用 PHP 进行用户注册,我正在尝试检查 INSERT 之后的用户帐户是否实际创建。我究竟做错了什么? $dataR变量什么都不返回,所以每次注册后都会创建账号,但是脚本还是返回“对不起,您的注册失败,请返回再试一次。”
感谢回复,欢迎提问!
连接:
$this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
注册.php:
$username = $this->db_connection->real_escape_string(strip_tags($_POST['username'], ENT_QUOTES));
$useremail = $this->db_connection->real_escape_string(strip_tags($_POST['email'], ENT_QUOTES));
$password = $_POST['password_new'];
$options = [
'cost' => 10,
];
$salt = $this->random_str(64);
$salted_password = $password . $salt;
$password_hash = password_hash($salted_password, PASSWORD_BCRYPT, $options);
$query = $this->db_connection->prepare("SELECT name, mail FROM users WHERE name = ? OR mail = ?");
$query->bind_param('ss', $username, $useremail);
$query->execute();
$results = $query->get_result(); // this works fine
if($results->num_rows == 1) {
$row = $results->fetch_object();
if($username == $row->name) {
$this->errors[] = "This username is already taken!";
} elseif($useremail == $row->mail) {
$this->errors[] = "This email address is already taken!";
} else {
$this->errors[] = "This username / email address is already taken.";
}
} else {
$SIS = new SnowflakeIdService;
$snowflakeID = $SIS->CreateSnowflakeID();
$sql = $this->db_connection->prepare("INSERT INTO users (snowflake, name, salt, hash, mail) VALUES (?, ?, ?, ?, ?)");
$sql->bind_param("issss", $snowflakeID, $username, $salt, $password_hash, $useremail);
$sql->execute();
$dataR = $sql->get_result(); // this not
if($dataR) {
$this->messages[] = "Your account has been created successfully. You can now log in.";
} else {
$this->errors[] = "Sorry, your registration failed. Please go back and try again.";
}
}
【问题讨论】:
-
因为只有插入状态 True/False 没有结果
-
如果您想知道是否插入了任何内容,请使用
$stmt->affected_rows。 -
BIG NOTE
password_hash()生成自己的 SALT,比您可能想出的任何东西都要好。如果您查看手册页是说Warning The salt option is deprecated. It is now preferred to simply use the salt that is generated by default. As of PHP 8.0.0, an explicitly given salt is ignored. -
另一个注意事项:如果你使用准备好的、绑定的、参数化的查询(就像你一样),你不需要
real_escape_string()用户输入 -
不要使用
$this->db_connection->real_escape_string(strip_tags会损坏你的数据。