我有 HTML 表单来获取姓名和密码。Python 代码用于获取输入数据并存储在变量first_name 和密码中。
对于给定的名称,存储的密码是使用 WHERE 子句从数据库中获取的。 通过使用 if 条件,我尝试比较从数据库获取的密码和从表单输入的密码。如果它们相等,则执行一些操作。如果不执行其他条件。但问题是我无法理解如何分配如果条件. 我尝试过的如下:
#!"C:\python34\python.exe"
import cgitb ,cgi
import sys
import mysql.connector
cgitb.enable()
form = cgi.FieldStorage()
print("Content-Type: text/html;charset=utf-8")
print()
# Get data from fields
first_name = form.getvalue('first_name')
password = form.getvalue('pass')
print (password)
conn = mysql.connector.connect(host='localhost',port='8051',
database='test',
user='root',
password='next')
cursor = conn.cursor()
if conn.is_connected():
print('Connected to MySQL database')
cursor.execute("""SELECT pass FROM tablename1 where name = '%s'""" % (first_name))
for row in cursor():
if(password == row):
print("sucess")
else:
print("fail")
请检查我的代码。并提出一些建议。
当用户第一次注册时,您应该像这样保存他的密码:
$password = password_hash("rasmuslerdorf", PASSWORD_DEFAULT);
这应该输出类似
$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a
的内容
你应该将其存储在你的数据库中。
然后你应该像这样验证密码:
<?php
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq'; // you get it from your database
if (password_verify('rasmuslerdorf', $hash)) { // 'rasmuslerdorf' is what user entered
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
?>
现在,什么是哈希?请阅读此。
编辑:你的意思是这样的?
cursor.execute("SELECT * FROM users WHERE username= ? and password= ?",
(username, pass1))
found = cursor.fetchone()
if found:
# user exists and password matches
else:
# user does not exist or password does not match
哈哈这是我迟来的答案,
cursor.execute(f"SELECT Password FROM users WHERE username= '{username}';")
found = cursor.fetchone()
for row in found:
if found == row:
# user exists and password matches
else:
# user does not exist or password does not match