How to avoid the below error in Python Flask - python

I am using the below 3 html i.e. Index.html , Results.html and Edit.html
and python code file app.py code is also pasted below.
The save to the DB is working fine and when I retrieve the data for editing and click on Submit I am encountering the below error
"_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s' at line 1")"
Index.html
<h1>Welcome</h1>
<br>
<br>
<form method="POST" action="{{ url_for('index') }}">
Name <input type="text" name="name" />
<br>
Email <input type="email" name="email" />
<br>
CRType <select name = "CRType">
<option value = "New">New</option>
<option value = "Old">Old</option>
</select><br>
<input type="submit" value="Submit">
</form>
Results.html
Add CR
<table border = 1>
{% for user in userDetails %}
<tr>
<td> {{user[3]}} </td>
<td> {{user[0]}} </td>
<td> {{user[1]}} </td>
<td> {{user[2]}} </td>
<td> Edit Profile </td>
</tr>
{% endfor %}
</table>
Edit.html
h1>Welcome to Update Zone</h1>
<br>
<br>
<body>
<form method="POST" action="{{ url_for('Edit') }}">
CR_ID <input type="text" name="CR_ID" value = "{{user[0]}}"/>
<br>
Name <input type="text" name="name" value = "{{user[1]}}"/>
<br>
Email <input type="email" name="email" value = "{{user[2]}}"/>
<br>
<br>
<input type="submit" value="Submit">
</body>
</form>
App.PY
from flask import Flask, render_template, request, redirect
from flask_mysqldb import MySQL
# from flask_table import Table, Col, LinkCol
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#$$w0rd'
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']
CRType = userDetails['CRType']
# CR_ID = userDetails['CR_ID']
cur = mysql.connection.cursor()
# cur.execute("""INSERT INTO users(name, email, CRType) VALUES(%s, %s, % )""",(name, email, CRType)
cur.execute("""INSERT INTO users (name, email, CRType) VALUES (%s, %s, %s)""", (name, email, CRType))
mysql.connection.commit()
cur.close()
return redirect ('/results')
# return redirect('/results')
return render_template('index.html')
#app.route('/results')
def results():
cur = mysql.connection.cursor()
resultValue = cur.execute("SELECT * from users")
if resultValue > 0:
userDetails = cur.fetchall()
# edit = LinkCol('Edit', 'edit', url_kwargs=dict(id='CR_ID'))
return render_template('results.html',userDetails=userDetails)
#app.route('/Edit', methods=['GET', 'POST'])
def Edit():
# request.method == 'GET':
# Fetch form data
# user = request.form
# CR_ID = user['CR_ID']
CR_ID = request.args.get('CR_ID')
name = request.args.get('name')
email = request.args.get('email')
CRType = request.args.get('CRType')
cur = mysql.connection.cursor()
# result= cur.execute("SELECT CR_ID, name, email from users where CR_ID = 1")
result = cur.execute("""SELECT CR_ID, name, email from users where CR_ID = %s""",CR_ID)
# result = cur.execute("Update table users set name=?, email=?, CRType=? where CR_ID = %s", CR_ID)
RV = cur.fetchall()
user = RV[0]
cur.close()
return render_template('Edit.html',user=user)
if __name__ == '__main__':
app.run(debug= True)

Your SQL statements aren't properly formatted. It should be
result = cur.execute("SELECT CR_ID, name, email from users where CR_ID = %s", (CR_ID))

Related

jinja2 UndefinedError: 'resultado' is undefined | FLASK

I'm working with Flask. I have one route and I want to redirect it to other route when pressing a button, but I want to pass an argument. This is my route:
#app.route('/actualize_product.html', methods=['GET', 'POST'])
def actualize_product():
if request.method == 'POST':
print("post")
query1 = """
SELECT id FROM BD.producto
WHERE id=""" + str(request.form['product_id'])
conection = connect()
resultt = conection.execute(query1)[0]
print(resultt)
return redirect(url_for('/edit_product.html', resultado = resultt)) #Line where I'm redirecting
query = "SELECT * FROM BD.Producto ALLOW FILTERING; "
conection = connect()
result = conection.execute(query)
return render_template('actualize_product.html', products = result)
And this is the route I want it to be redirected
#app.route('/edit_product.html', methods=['GET', 'POST'])
def edit_product():
print("edit")
if request.method == 'POST':
print("Im already here")
return render_template('edit_product.html')
The problem is that the edit_product.html is a file where I use jinja2
<h2>Id del producto: {{resultado.id}} </h2> <br>
<form action="app.py" method="get" onsubmit="return formEsValido()">
<input type= "hidden" value = "{{resultado.id}}" id = "id" name = "id">
<label for="product_name"> Nuevo nombre del Producto: </label>
<input type="text" name="product_name" id="product_name" class="form-control">
<label for="product_price"> Nuevo precio del Producto: </label>
<input type="text" name="product_price" id="product_price" class="form-control">
<label for="descripction"> Nueva descripcion del Producto: </label>
<input type="text" name="description" id="description" class="form-control">
<label for="stock">Nuevo stock del Producto</label>
<input type="text" name="stock" id="stock" class="form-control">
<br>
<button class="btn btn-primary"id="index-buttons" type="submit">Editar Producto</button>
</form>
</div>
If I use render_template instead of redirect, it won't work because after clicking on that button, the route will be /actualize_product.html and I want it to change to /edit_product.html' because I have a form there, I don't know how to pass that variable called "resultado" to jinja2 using redirect.
If all you need is the id, you can pass it as an url parameter.
#app.route('/actualize')
def actualize():
return redirect(url_for('edit', id=123))
#app.route('/edit')
def edit():
id = request.args.get('id')
return render_template('edit.html', id=id)

variable is undefined flask mysql

I need to greet user on the page. F.ex: Hello {{ name }}, but I get the error UnboundLocalError: local variable 'account' referenced before assignment. What is the problem in the code below?
python:
app = Flask(__name__)
mysql = MySQL(app)
#app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
cur = mysql.connection.cursor()
cur.execute('INSERT INTO users(name, email) VALUES(%s, %s)', (name, email))
mysql.connection.commit()
cur.close()
return redirect('profile')
return render_template('index.html')
#app.route('/profile', methods=['GET'])
def profile():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
cur = mysql.connection.cursor()
cur.execute('SELECT * FROM users')
account = cur.fetchone()
return render_template('profile.html', account=account)
index.html:
<form action="" method="POST">
<span style="color: #fff;">Firstname:</span><input type="text" name="name" placeholder="Type your firstname"><br><br>
<input type="submit" name="submit" value="submit">
</form>
profile.html
<h4 style="color: #fff;">Your firstname: is {{ account['name'] }}</h4>
<h4 style="color: #fff;">Your email: is {{ account['email'] }}</h4>
I can connect to database and fetch users data, but on the profile.html page I get the error
How to solve it? Please help.
You haven't passed the account to the template.
Instead of ,
return render_template('profile.html')
you need to write as,
return render_template('profile.html', account=account)
EDIT:
#app.route('/profile', methods=['GET','POST'])
def profile():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
cur = mysql.connection.cursor()
cur.execute('SELECT * FROM users')
account = cur.fetchone()
return render_template('profile.html', account=account)
Or if you wanted the profile to be a get request you can do this
#app.route('/profile', methods=['GET','POST'])
def profile():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
cur = mysql.connection.cursor()
cur.execute('SELECT * FROM users')
account = cur.fetchone()
return render_template('profile.html', account=account)

unable to fetch certain table from database corresponding to selected value from selection box using python

This question could be duplicate but I have checked all the answers of such related questions and I haven't been able to solve it .
I am trying to get the value from a drop down menu and retrieve certain table from database corresponding to this value .
here is the python file
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="mysql",
database="SugeryClinicDataBase"
)
mycursor = mydb.cursor()
from flask import Flask, redirect, url_for, request,render_template
app = Flask(__name__)
#app.route('/login',methods = ['POST', 'GET'])
def login():
if request.method == 'POST': ##check if there is post data
Username = request.form['name']
Password = request.form['id']
Selection = request.form['myselectbox']
#value= request.form['']
if Selection==Patient:
mycursor.execute= "SELECT * FROM Patients JOIN DOC_PAT on Patients.id = DOC_PAT.P_code Where Patients.id = PassWord"
myresult = mycursor.fetchall()
for x in myresult:
print(x)
elif Selection==Doctor:
mycursor.execute= "SELECT * FROM Doctors "
myresult = mycursor.fetchall()
for x in myresult:
print(x)
else:
return render_template ('doctors.html')
if __name__ == '__main__':
app.run()
Here is Html file
<!DOCTYPE html>
<form action='' method="POST">
Username:<br>
<input type="text" name="name" value="example">
<br>
Password :<br>
<input type="number" name="id" value="10">
<br>
Selection : <br>
<select name="myselectbox" class="form-control" id="exampleFormControlSelect1" value="">
<br>
<option value="a">choose</option><br>
<option value="b">Patient</option><br>
<option value="c">Doctor</option><br>
<option value="d">Other</option>
</select>
<br> <br>
<input type="submit" value="Submit">
</form>
I am facing this error :
NameError: global name 'Patient' is not defined

How to Edit Data in Web App Flask and SQL server?

I created a web app Flask. I use pyodbc for connect to SQL SERVER database. I display Tbl_product with #app.route('/product'). tbl_product is a table with 4 columns: P_ID, title, count, price. I want to click on Edit of each row in product page and go to Edit page with values of title,count and price same row as default.Then I want to edit this information and return to product page.
my app.py is:
from flask import Flask,render_template,url_for, request, redirect, flash
import pyodbc
app = Flask(__name__)
conn = pyodbc.connect('Driver={SQL Server};'
'Server=TABRIZIYAN;'
'Database=market_DB;'
'Trusted_Connection=yes;')
#app.route('/product')
def product():
cursor = conn.cursor()
resultValue=cursor.execute("SELECT * FROM Tbl_product")
#if resultValue > 0:
productDetails= cursor.fetchall()
cursor.close()
return render_template('product.html', productDetails=productDetails)
#app.route('/edit', methods=['GET','POST'])
def update():
if request.method =='POST':
#fetch form data
productDetails= request.form
P_ID=productDetails['P_ID']
title= productDetails['title']
count=productDetails['count']
price= productDetails['price']
cursor = conn.cursor()
cursor.execute("UPDATE Tbl_product SET title=?, count=?, price=? WHERE P_ID=?",
(title,count,price,P_ID))
conn.commit()
cursor.close()
return redirect('/product')
return (render_template('edit.html'))
my product.html is:
<table bolder= 1px>
<tr>
<td> ID </td>
<td> Title </td>
<td> Count </td>
<td> Price </td>
<td> Action </td>
</tr>
{% for product in productDetails %}
<tr>
<td> {{product[0]}} </td>
<td> {{product[1]}} </td>
<td> {{product[2]}} </td>
<td> {{product[3]}} </td>
<td> <a href='/edit/{{product[0]}}'>Edit</a></td>
</tr>
{% endfor %}
my edit.html is:
<form method="Post" action="">
<h1> Edit product </h1>
ID<br>
<input type="text" name="P_ID"><br>
Title<br>
<input type="text" name="title"><br>
Count<br>
<input type="text" name="count"><br>
Price<br>
<input type="text" name="price"><br>
<br>
<input type="submit">
</form>
How I do it?
My answer is:
app.py changed as below :
#app.route('/product')
def product():
cursor = conn.cursor()
cursor.execute("SELECT * FROM Tbl_product")
productDetails= cursor.fetchall()
return render_template('product.html',
productDetails=productDetails)
#app.route('/edit/<string:P_ID>', methods=
['GET','POST'])
def update(P_ID):
if request.method=='GET':
cursor=conn.cursor()
productDetails1=cursor.execute("SELECT * FROM Tbl_product WHERE P_ID=?",
(P_ID))
productDetails1= cursor.fetchall()
conn.commit()
cursor.close()
return (render_template("edit.html", productDetails1=productDetails1))
if request.method =='POST':
#fetch form data
productDetails= request.form
#P_ID=productDetails['P_ID']
title= productDetails['title']
count=productDetails['count']
price= productDetails['price']
cursor = conn.cursor()
cursor.execute("UPDATE Tbl_product SET title=?, count=?, price=?, active=?
WHERE P_ID=?",(title,count,price,active,P_ID))
conn.commit()
cursor.close()
flash("Data Updated Successfully")
return redirect('/product')
edit.html changed as below :
<form method="Post" action="">
<h1> Edit Product Page </h1>
{% for product in productDetails1 %}
<input type="hidden" name="P_ID" value={{product[0]}}" ><br>
Title:<br>
<input type="text" name="title" value="{{product[1]}}"><br>
Count:<br>
<input type="text" name="count" value="{{product[2]}}"><br>
Price:<br>
<input type="text" name="price" value="{{product[3]}}" ><br><br>
{% endfor %}
<br>
<input type="submit" value="Edit">
</form>

Flask + Sqlite3 incorrect formatting

I am building a website where people can apply for the team, it's been going well so far however when I display the applications on a page, this shows up.
(' IGN:\r\n Age:\r\n Server Proxy:\r\n Nationality:\r\n TeamSpeak?:\r\n Discord?:\r\n Twitter?:\r\n YouTube?:\r\n Requirement Option:\r\n Exceptions:\r\n Current Clans?:\r\n Why Ominous?:\r\n\t\t\t\t\t\t',)
The textarea looks like this,
</header>
<h1>Enter Application</h1>
<form action="/memberapp" method="POST">
<textarea type="text" name="text" size="350" rows="13">
IGN:
Age:
Server Proxy:
Nationality:
TeamSpeak?:
Discord?:
Twitter?:
YouTube?:
Requirement Option:
Exceptions:
Current Clans?:
Why Ominous?:
</textarea>
<br>
<input type="submit" name="my-form" value="Submit">
The way I am inserting the data looks like this:
text = request.form['text']
connect()
conn = sqlite3.connect("main.db")
c = conn.cursor()
c.execute("INSERT INTO memberapps VALUES(?)", (text,))
conn.commit()
conn.close()
conn = sqlite3.connect("main.db")
That isn't the issue however, finally, the way I am displaying it is like so:
conn = sqlite3.connect("main.db")
c = conn.cursor()
c.execute("SELECT * FROM memberapps")
r = c.fetchall()
conn.close()
return render_template('member-view.html', rows=r)
{% for r in rows %}
<h2>{{r}}</h2>
{% endfor %}
Thanks!

Categories

Resources