2017-11-18 93 views
0

我在HTML中有三个复选框,并且我在Python中获得了复选框值。如果我选​​中复选框,则意味着值应该在MYSQL数据库中插入为“yes”,否则应该是提前插入为“无”。我曾尝试,但我不知道怎么弄Answer.Please帮我,谢谢:)如何在MYSQL中使用Flask插入复选框值

这里是我的代码: HTML:

<form action='/hello' method="POST" enctype="multipart/form-data"> 
Panchayath <input type="checkbox" name="checks[]" value="yes" id="panchayath"><br> 
    Ward <input type="checkbox" name="check[]" value=" yes" id=" ward"><br> 
    Results <input type="checkbox" name="chec[]" value=" yes" id=" results"> 
    <input type="submit" value="Submit"> 
</form> 

潘岳:

import os 
from flask import Flask, request, render_template 
from flaskext.mysql import MySQL 

mysql = MySQL() 

app = Flask(__name__) 
app.config['MYSQL_DATABASE_USER'] = 'root' 
app.config['MYSQL_DATABASE_PASSWORD'] = 'root' 
app.config['MYSQL_DATABASE_DB'] = 'bucketlist' 
app.config['MYSQL_DATABASE_HOST'] = 'localhost' 
mysql.init_app(app) 
APP_ROOT = os.path.dirname(os.path.abspath(__file__)) 


@app.route('/hello', methods=['GET', 'POST']) 
def get_data(): 
    print("hlo") 
    if request.method == 'POST': 
     print("cat") 
     panchayath = request.form.getlist('checks[]') 
     print panchayath 
     ward = request.form.getlist('check[]') 
     print ward 
     Results = request.form.getlist('chec[]') 
     print Results 
     conn = mysql.connect() 
     cursor = conn.cursor() 
     # cursor.execute() 
     print "yes" 
     # cursor.execute("insert into try_chk3 values (%s,%s,%s)", (some_var)) 
     # query = "CREATE TABLE saracheck(panchayath VARCHAR(40), ward VARCHAR(40),Results VARCHAR (40))" 
     # cursor.execute(query) 
     query = "INSERT INTO saracheck(panchayath,ward,Results) VALUES(%s,%s,%s)" 
     a=cursor.execute(query, (panchayath,ward,Results)) 
     print a 
     print "execuet" 
     # cursor.execute(query,(first_name,last_name,email_id,can_pic,logo_pic)) 
     conn.commit() 


    return render_template("form.html") 


if __name__ == '__main__': 
    app.run() 

输出: enter image description here

回答

0

首先,你为什么要命名的领域,如“检查”,“检查”和“中港”,它要么好像所有的人都将是名称=“检查[]”或它的只是不好的命名风格。

也不是你想要获得所有三个字段的值?那么你应该试图让他们全部三个Results是正确的?

你可以请你也发布你到目前为止的输出吗?

+0

我是新来的python,我想插入复选框值在数据库中,如果它被检查? – sara

+0

我发布上面的输出页面 – sara