我想在点击“登录”时检查用户是否存在于数据库中。如果是,则回显“用户存在”,否则“用户不存在”。我怎么能这样做?到目前为止我有:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
</head>
<body>
<form method="post" action="login.php">
Username: <input type="text" value="" name="username" /><br /><br />
Password: <input type="password" value="" name="password" /><br /><br />
<input type="submit" name="submit" value="Log In"/>
</form>
</body>
</html>
答案 0 :(得分:2)
试试这个
session_start();
if($_SERVER['REQUEST_METHOD'] === 'POST'){
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user = $conn->real_escape_string(htmlspecialchars(trim($_POST['username'])));
$query = "SELECT `username` FROM `users` WHERE `username` = '$user'";
$result = $conn->query($query);
if($result->num_rows > 0) {
$_SESSION['allowToWelcome'] = true;
header('Location:welcome.php');
die();
}
else $message = 'user does not exist';
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
</head>
<body>
<form method="post" action="login.php" enctype="multipart/form-data">
<?php if(isset($message)) : ?>
<div class="error"><?php echo $message; ?></div>
<?php endif; ?>
Username: <input type="text" value="" name="username" /><br /><br />
Password: <input type="password" value="" name="password" /><br /><br />
<input type="submit" name="submit" value="Log In"/>
</form>
</body>
</html>
在welcome.php中你可以像这样检查
session_start();
if(!isset($_SESSION['allowToWelcome'])){
header('Location:login.php');
die();
}
答案 1 :(得分:1)
在我制作的登录/注册脚本中,我使用了类似的东西..
// check existing username
$prep_stmt = "SELECT id FROM your-table-name WHERE username = ? LIMIT 1";
$stmt = $mysqli->prepare($prep_stmt);
if ($stmt) {
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
// A user with this username already exists
$error_msg .= '<p class="error">A user with this username already exists</p>';
$stmt->close();
}
$stmt->close();
} else {
$error_msg .= '<p class="error">Database error line 55</p>';
$stmt->close();
}