我在Flask中使用以下代码将值存储在MySQL DB中。我只存储从html页面输入的2个值
from flask import Flask, render_template, request, redirect
from flask_mysqldb import MySQL
app = Flask(__name__)
# Configure db
#db = yaml.load(open('db.yaml'))
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
#app.config['MYSQL_PASSWORD'] = 'P******'
app.config['MYSQL_DB'] = 'flaskapp'
mysql = MySQL(app)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
# Fetch form data
userDetails = request.form
name = userDetails['name']
email = userDetails['email']
type = userDetails['type']
cur = mysql.connection.cursor()
cur.execute("INSERT INTO users(name, email, type) VALUES(%s, %s, %s)", name, email, type([0],[1]))
mysql.connection.commit()
cur.close()
return 'Save is Successful'
return render_template('index.html')
@app.route('/users')
def users():
cur = mysql.connection.cursor()
resultValue = cur.execute("SELECT * FROM users")
if resultValue > 0:
userDetails = cur.fetchall()
return render_template('users.html',userDetails=userDetails)
if __name__ == '__main__':
app.run(debug= True)
我的HTML页面
我有一个下拉列表。输入名称和电子邮件后,需要选择类型并将所有三个值存储在DB中。
不知道怎么做。
答案 0 :(得分:0)
确保在HTML中提供正确的 id ,如下所示:
<select id="type">
<option selected value="1">New</option>
<option value="0">Old</option>
</select>
然后读取服务器端的数据:
type = request.form.get('type')
我还建议更改var名称&#34;输入&#34;更详细的东西。