86 lines
2.5 KiB
PHP
86 lines
2.5 KiB
PHP
<?php
|
|
|
|
class UserManage
|
|
{
|
|
private ?mysqli $mysqli;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->mysqli = $this->dbConnect();
|
|
}
|
|
|
|
/**
|
|
* @return mysqli|void
|
|
*/
|
|
private function dbConnect()
|
|
{
|
|
$mysqli = mysqli_connect('localhost', 'root', 'chenx221') or die('数据库连接错误' . mysqli_connect_error());
|
|
mysqli_select_db($mysqli, 'db_database15') or die('数据库访问失败,请检查数据库db_database15是否存在');
|
|
mysqli_set_charset($mysqli, 'utf8mb4');
|
|
return $mysqli;
|
|
}
|
|
|
|
public function __destruct()
|
|
{
|
|
mysqli_close($this->mysqli);
|
|
}
|
|
|
|
/**
|
|
* @param $username
|
|
* @param $password
|
|
* @return void
|
|
*/
|
|
public function registerUser($username, $password): void
|
|
{
|
|
$stmt = $this->mysqli->prepare("select username from tb_user where username = ?");
|
|
$stmt->bind_param("s", $username);
|
|
$stmt->execute();
|
|
$user = null;
|
|
$stmt->bind_result($user);
|
|
$stmt->fetch();
|
|
$stmt->close();
|
|
|
|
if ($user != null) {
|
|
echo '<script>alert("username already exists")</script>';
|
|
} else {
|
|
$enc_password = password_hash($password, PASSWORD_DEFAULT);
|
|
$stmt = $this->mysqli->prepare("insert into tb_user (username, password) values (?, ?)");
|
|
$stmt->bind_param("ss", $username, $enc_password);
|
|
$stmt->execute();
|
|
$result = $stmt->affected_rows;
|
|
$stmt->close();
|
|
if ($result == 1) {
|
|
echo '<script>alert("register success")</script>';
|
|
} else {
|
|
echo '<script>alert("register failed")</script>';
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @param $username
|
|
* @param $password
|
|
* @return void
|
|
*/
|
|
public function loginUser($username, $password): void
|
|
{
|
|
$enc_password = null;
|
|
$stmt = $this->mysqli->prepare("select password from tb_user where username = ?");
|
|
$stmt->bind_param("s", $username);
|
|
$stmt->execute();
|
|
$stmt->bind_result($enc_password);
|
|
$stmt->fetch();
|
|
$stmt->close();
|
|
|
|
if ($enc_password != null) {
|
|
if (password_verify($password, $enc_password)) {
|
|
echo '<script>alert("login success")</script>';
|
|
} else {
|
|
echo '<script>alert("Password is wrong")</script>';
|
|
}
|
|
} else {
|
|
echo '<script>alert("username not exists")</script>';
|
|
}
|
|
}
|
|
|
|
} |