Reputation: 171
Hi guys I am trying to pass information from and HTML page into a MySQL database via flask but im stuck and confused
This is my python - scores.py (Database connection is conn_db with credentials etc)
import mysql.connector as conn
from flask import (
render_template,
Flask,
jsonify,
request,
abort as ab
)
app = Flask(__name__, template_folder='C:\\Users\\thomp\\PycharmProjects\\com661_1819_team_30\\source\\template\\')
# Credentials here in code
WHO = '*********'
PWD = '********'
DATABASE = '********'
def conn_db():
return conn.connect(user=WHO,
password=PWD,
host='**********',
database=DATABASE
)
@app.route('/')
def index():
return render_template('scores.html')
@app.route('/addScore', methods=['POST'])
def add_score():
cnx = conn_db()
cursor = cnx.cursor()
MatchID = request.form['matchID']
Home_Score = request.form['homeScore']
Away_Score = request.form['awayScore']
print("Updating score")
if not request.json:
ab(400)
insert_score = "INSERT INTO scores (Match_ID, Home_Score, Away_Score) VALUES (%s,%s,%s)"
cursor.execute(insert_score, (MatchID, Home_Score, Away_Score))
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
And the following is my html file scores.html ( Posted as picture )
Any help is greatly appreciated, thanks guys
Upvotes: 0
Views: 848
Reputation: 1042
From what you have given us I suppose one of your problems is that you're not posting the contents of your input fields, but rather the DOM object itself. If you're unsure about javascript code it's always a good idea to try it out in your browser's developer console.
To fix that error just add val()
to the submit function, e.g.
var $matchID = $('#matchID').val()
Also I think you should remove the trailing slash from the host parameter of your AJAX call because you defined your route in flask without it.
Two side notes:
conn.escape_string()
for this purpose.PS: It would be very helpful if you posted a specific question or any error output that you're encountering. Also posting screenshots instead of the actual code seems unnecessary and makes it way harder to debug your problems.
Upvotes: 1
Reputation: 35
I have recently done the exact same thing, so I'll share with you what I have done to allow changing of SQL data via HTML.
Just like you I retrained information from the HTML page with a request form
report_name = request.form["report_name"]
followed by
cur.execute("UPDATE table SET report_name=%s", [report_name])
mysql.connection.commit()
I only had to update my tabled, but it might be possible to change that with Insert Into.
Upvotes: 0