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!
Related
Im trying to fetch users from my sql database with sqlite 3 and displaying the names in a form to pick 2 and set up a match. But when i pass the variables through only my first jinja for loop runs and it leaves the second multiple selection box empty.
I've tried it with passing the same variable for both loops and different variables one for each, and the second one still doesn't populate.
from flask import Flask
from flask import render_template
import sqlite3
con = con = sqlite3.connect('chess-test.db')
cur = con.cursor()
app = Flask(__name__)
#app.route('/')
def index():
users = cur.execute('''SELECT * FROM chess ORDER BY hcp ''')
return render_template("index.html", users=users)
#app.route('/game')
def game():
names = cur.execute('''SELECT * FROM chess ORDER BY name ''')
users = cur.execute('''SELECT * FROM chess ORDER BY name ''')
return render_template("game.html", names1=names, users=users)
and my jinja template looks like this.
<body>
<div class="container">
<div class="text-center">
<div class="display-4">Hvem skal spille?</div>
</div>
<div class="form-group">
<select multiple class="form-control">
{% for item in names1 %}
<option>{{ item[0] }}</option>
{% endfor %}
</select>
<label for="exampleFormControlSelect2">mod</label>
<select multiple class="form-control">
{% for item in users %}
<option>{{ item[0] }}</option>
{% endfor %}
</select>
</div>
</div>
and here is the resulting page.
Read the queryset before executing next query. Refer here
#app.route('/game')
def game():
cur.execute('''SELECT * FROM chess ORDER BY name ''')
names = cur.fetchall()
cur.execute('''SELECT * FROM chess ORDER BY name ''')
users = cur.fetchall()
return render_template("game.html", names1=names, users=users)
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
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))
This question already has answers here:
Get the data received in a Flask request
(23 answers)
How to use variables in SQL statement in Python?
(5 answers)
Closed 4 years ago.
I have an HTML form that looks like this:
<form>
Event Name:<br>
<input type="text" name="eventname">
<br>
Sports:<br>
<select name = "dropdown">
<option value = "soccer">Soccer</option>
<option value = "basketball">Basketball</option>
<option value = "baseball">Baseball</option>
<option value = "football">Football</option>
</select>
<br>
Location:<br>
<input type="text" name="location">
<br>
Time:<br>
<input type="text" name="time">
<br>
Number of Players:<br>
<input type="text" name="numplayers">
<br>
Minimum Age:<br>
<input type="text" name="minage">
<br>
Maximum Age:<br>
<input type="text" name="maxage">
<br>
Minimum Skill Level:<br>
<input type = "radio" name = "minskill" value = "1"> 1
<input type = "radio" name = "minskill" value = "2"> 2
<input type = "radio" name = "minskill" value = "3"> 3
<input type = "radio" name = "minskill" value = "4"> 4
<input type = "radio" name = "minskill" value = "5"> 5
<br>
Maximum Skill Level:<br>
<input type = "radio" name = "maxskill" value = "1"> 1
<input type = "radio" name = "maxskill" value = "2"> 2
<input type = "radio" name = "maxskill" value = "3"> 3
<input type = "radio" name = "maxskill" value = "4"> 4
<input type = "radio" name = "maxskill" value = "5"> 5
<br>
<br>
<input type="submit" value="Submit">
</form>
Looks Like:
This pretty much gets the information needed to create an event.
My goal is to use the following query to post a data into my MySQL database:
INSERT INTO Events(EventName, Sports, Location, Time, NumPlayers, MinAge, MaxAge, MinSkill, MaxSkill)
where the values are the values that the users type into the input form.
In my routes.py file, where I use flask and MySQLdb, I try to execute a SQL query as follows:
from flask import *
from functools import wraps
import MySQLdb
conn = MySQLdb.connect(...)
#app.route('/hello')
#login_required
def hello():
cursor = conn.cursor()
cursor.execute("SELECT * FROM sports")
rows = cursor.fetchall()
data = [row for row in rows]
cursor.close()
return render_template('hello.html', data = data)
HTML that displays the info above:
<h3>Sports Data</h3>
{% for item in data %}
{{ item }}<br/>
{% endfor %}
This successfully displays the data in the sports table.
But I have no idea how I should use the input form data to insert the event data into my MySQL database.
Please help!
I'm not familiar with python since I work in php, but your sql syntax should be the following:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Just make sure your name field in the html form correspond with column names in the database table.
Hope this helps!
I'm getting a bad value when I return this option. For example, when i send n = "Arnold, Robert | ID: 1" as an option, it shows up on the web page, but when the user clicks submit, only "Arnold," is sent to my Flask Server. I'm trying to get the ID value out.
Does anyone know how to retrieve the entire option value from the form or another way to get the ID out of the string?
Here's the HTML
<h2>Donors</h2>
<form method="POST" action="/display_donor">
<select name="selected_donor">
{% for n in donors %}
<option value={{n}}>{{n}}</option>
{% endfor %}
</select>
<br />
<br><input type="submit" value="View donor"/>
</form>
Here's the relevant Flask function
#app.route('/display_donor', methods=['POST'])
def display_donor():
temp_id = request.form['selected_donor']
print "temp_id"
print temp_id
final_id = re.sub('[^0-9]','', temp_id)
print "final_id"
print final_id
display_value = 1
cursor = g.conn.execute("SELECT name,donor_id FROM donors")
donors = []
for result in cursor:
temp_string = result['name'] + " | ID: " +result['donor_id']
donors.append(temp_string)
# can also be accessed using result[0]
cursor.close()
print "this"
print final_id
#Returns a specific instance of transaction as specified by user
cursor = g.conn.execute("SELECT * FROM donors D WHERE D.donor_id='%s'" % final_id)
values = []
for result in cursor:
values.append(result['donor_id'])
values.append(result['name'])
values.append(result['donor_type'])
cursor.close()
#denote attribute names
attribute = []
attribute.append('donor_id')
attribute.append('name')
attribute.append('donor_type')
return render_template("donors.html",attribute=attribute,values=values,donors=donors,display_value=display_value)
I fixed this issue by sending the values separately rather than as a single string. This got me out of all the parsing and allowed me to print out the values like so:
<h2>Donors</h2>
<form method="POST" action="/display_donor">
<select name="selected_donor">
{% for n in donor_ids %}
<option value={{n}}>{{ donor_names[loop.index0] }} | ID: {{n}}</option>
{% endfor %}
</select>
<br />
<br><input type="submit" value="View donor"/>
</form>