Search code examples
htmlmysqlflaskmysql-python

Display data on html from mysql database using flask


I been stuck on how to display data on html from mysql database using flask.

My connection to database is successful and html page displays. Just doesn't display with the data

Would like to display the "info_table" from the database. Has 2 attribute "name" and "age"

Is line "app.route('/display', methods=['GET'])" correct?

app.py


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

app = Flask(__name__)
app.debug = True

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

mysql = MySQL(app)


app.route('/display', methods=['GET'])
def display():
    cursor = mysql.connection.cursor()
    cursor.execute("SELECT * FROM info_table")
    data = cursor.fetchall()
    return render_template('display.html', info_table=data)


app.run(host='localhost', port=3306)

display.html:

t<!DOCTYPE html>
<html>
<head>
 <title></title>
</head>
<body>
<style>

 td {
        width: 150px;
        text-align: center;
        border: 1px solid black;
        padding: 5px;
      }
</style>
<table>
  <thead>
    <tr>
        <th>name</th>
        <th>age </th>
    </tr>
    </thead>
    <tbody>
     {% for row in data %}
            <tr>
                <td>{{row[0]}}</td>
                <td>{{row[1]}}</td>
            </tr>
        {% endfor %}
    </tbody>
</table>
</body>
</html>

Solution

  • First of all I need to thank you that you're keep trying and asking.

    Regarding request handler in app.py app.route('/display', methods=['GET']) you should define it as a decorator like this @app.route('/display', methods=['GET']) and then in display.html change the data variable to info_table in the for loop cause this is the real attribute that you're mapping data to it