0

I am trying to insert values to the mysql table using flask. When I run the code, I get the html page, I enter the details and click the submit button. I have used 'post' method and used flask request to get the data and used that to sql table. But, I am getting Bad request error. Below is the code.

from flask import Flask, render_template, request
from flask_mysqldb import MySQL

app = Flask(__name__)

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'HOTEL_MANAGEMENT'

mysql = MySQL(app)

@app.route('/', methods = ['GET', 'POST'])
def index():
    if request.method == "POST":
        # fetch form data
        userDetails = request.form
        Name = userDetails['Name']
        Address = userDetails['Address']
        Phone_no = userDetails['Phone_no']
        User_id = userDetails['User_id']
        Password = userDetails['Password']
        
        # Store in database mycursor
        mycursor = mysql.connection.cursor()
        # use hotel management database
        mycursor.execute("USE HOTEL_MANAGEMENT")
        mycursor.execute("""
        INSERT INTO Reg_details(Name, Address, Phone_no, User_id, Password)
        VALUES('{}','{}','{}','{}','{}')
        """.format(Name, Address, Phone_no, User_id, Password))
        # Commit the database
        mysql.connection.commit()
        mycursor.close()
        return 'success'
    
    return render_template("user_details.html")


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

Error

Bad request (400) The browser (or proxy) sent a request that this server could not understand.

What might be wrong which is creating the error?

Dan
  • 3,647
  • 5
  • 20
  • 26
Sunag
  • 105
  • 6
  • 1
    Does [this](https://stackoverflow.com/a/54169274/5320906) help? – snakecharmerb May 28 '22 at 13:07
  • I checked [this](https://stackoverflow.com/questions/46343308/what-is-http-400-bad-request-in-flask/54169274#54169274). I am able to understand but unable to solve the problem. – Sunag May 28 '22 at 13:22
  • The problem is one of 'Name', 'Address', 'Phone_no', 'User_id' or 'Password' are not included in the request. Check your form to make sure the `name` attribute matches exactly with the values you are trying to access. – Henry May 28 '22 at 13:46
  • It worked...Had some problem in html file – Sunag May 28 '22 at 15:02

0 Answers0