用mysql.connector和html写一个登录页面,并且可以验证账号密码正误,错误时提示密码错误
时间: 2024-02-05 14:11:34 浏览: 19
好的,我来为您演示一下如何使用mysql.connector和HTML写一个简单的登录页面,并验证账号密码的正确性。
首先,我们需要创建一个MySQL数据库,并在其中创建一个名为“users”的表,该表包含id、username和password字段。然后,我们将在Python中使用mysql.connector模块来连接数据库并验证用户的登录信息。
以下是HTML代码,显示一个简单的登录表单:
```html
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
<form action="login.py" method="post">
<label>Username:</label>
<input type="text" name="username"><br><br>
<label>Password:</label>
<input type="password" name="password"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
```
该表单将向login.py提交POST请求,我们将在该脚本中验证用户的登录信息。
接下来,我们来编写Python代码,连接到MySQL数据库并验证用户的登录信息。以下是login.py的代码:
```python
import mysql.connector
from mysql.connector import errorcode
import cgi
# 获取表单数据
form = cgi.FieldStorage()
username = form.getvalue('username')
password = form.getvalue('password')
# 数据库配置
config = {
'user': 'your_username',
'password': 'your_password',
'host': 'localhost',
'database': 'your_database',
'raise_on_warnings': True
}
# 连接到数据库
try:
cnx = mysql.connector.connect(**config)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your username or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
cursor = cnx.cursor()
# 查询用户信息
query = "SELECT id FROM users WHERE username = %s AND password = %s"
cursor.execute(query, (username, password))
result = cursor.fetchone()
# 验证用户是否存在
if result:
print("Content-Type: text/html")
print("")
print("<h1>Login Successful!</h1>")
else:
print("Content-Type: text/html")
print("")
print("<h1>Incorrect username or password</h1>")
cursor.close()
cnx.close()
```
该脚本首先获取POST请求中的用户名和密码。然后,它将使用mysql.connector模块连接到MySQL数据库。如果连接成功,它将执行一个SELECT语句来检查用户是否存在,并在成功或失败时输出相应的HTML消息。
最后,我们需要将login.py放在服务器上,并将HTML表单中的“action”属性设置为该脚本的URL。现在,当用户填写表单并单击“登录”按钮时,它将向login.py发送POST请求,并验证用户的登录信息。
希望这个例子能帮助您理解如何使用mysql.connector和HTML创建一个简单的登录页面。