用mysql.connector和html写一个登录页面,并且可以验证账号密码正误,错误时提示密码错误,正确则进入新的页面
时间: 2024-02-05 11:11:37 浏览: 21
以下是一个简单的实现:
1. 创建一个 MySQL 数据库,包含一个名为 `users` 的表,表中有两个字段:`username` 和 `password`。在表中添加一些用户账号和密码。
2. 创建一个 HTML 登录页面,包含两个输入框和一个登录按钮。
3. 使用 MySQL Connector Python 模块连接到数据库,并且定义一个函数 `login(username, password)`,用于验证用户输入的账号密码是否正确。
4. 在登录按钮点击事件中调用 `login()` 函数,如果验证成功则跳转到另一个 HTML 页面,否则在登录页面显示错误提示信息。
下面是代码示例:
HTML 文件 `login.html`:
```
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form>
<label>Username:</label>
<input type="text" id="username"><br>
<label>Password:</label>
<input type="password" id="password"><br>
<button type="button" onclick="login()">Login</button>
</form>
<div id="message"></div>
<script>
function login() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
if (xhr.responseText === 'success') {
window.location.href = 'welcome.html';
} else {
document.getElementById('message').innerHTML = 'Invalid username or password.';
}
} else {
document.getElementById('message').innerHTML = 'Error: ' + xhr.statusText;
}
}
};
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
xhr.open('POST', 'login.py');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('username=' + encodeURIComponent(username) + '&password=' + encodeURIComponent(password));
}
</script>
</body>
</html>
```
Python 文件 `login.py`:
```python
import mysql.connector
import cgi
# 连接到 MySQL 数据库
cnx = mysql.connector.connect(user='username', password='password', database='mydatabase')
def login(username, password):
cursor = cnx.cursor()
query = ("SELECT COUNT(*) FROM users WHERE username=%s AND password=%s")
cursor.execute(query, (username, password))
result = cursor.fetchone()[0]
cursor.close()
return result == 1
# 处理 POST 请求
form = cgi.FieldStorage()
username = form.getvalue('username')
password = form.getvalue('password')
if login(username, password):
print('Content-Type: text/plain')
print('Status: 200 OK')
print()
print('success')
else:
print('Content-Type: text/plain')
print('Status: 401 Unauthorized')
print()
print('invalid username or password')
```
HTML 文件 `welcome.html`:
```
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome</h1>
<p>You have successfully logged in.</p>
</body>
</html>
```
注意事项:
- 代码中的数据库连接信息需要根据实际情况进行修改。
- 为了简单起见,代码中没有对输入的用户名和密码进行安全性检查,实际开发中需要注意防止 SQL 注入等安全问题。