2

every time I try to display my data out of my MySQL database on a html page it will only show the first column of the record or only the name of the column itself.

For example:

MyDatabase

db

id  names
1   Harry
2   Snape

main.py

@app.route("/db", methodes = ["POST", "GET"])
def db():
    if request.method == "POST":
        cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cur.execute("SELECT names FROM db WHERE id = 1")
        output = cur.fetchone()
        cur. close 
        return render_template("db.html", data = output)
    else:
        return render_template("db.html")

db.html

{% extends "base.html" %}
{% block title %}db{% endblock %}

{% block content %}
<form method="POST">
<input type="submit" value="show data">
</form>

<!-- Output 1 -->
<p>{{data}}</p>

<!-- Output 2 -->
{% for i in data %}
    <p>{{i}}</p>
{% endfor %}

<!-- Output 3 -->
{% for i in data %}
    <p>{{i[0]}}</p>
{% endfor %}

{% endblock %}

Output 1 = {'names': 'Harry'}

Output 2 = names

Output 3 = n

I just want to get the records, not the column name, how can I do this (Output = Harry)

I am new to all this, I would be happy about a short explanation :)

2 Answers 2

2

you can search for Dictionary in Python .

here is some changes in your db.html code :

{% extends "base.html" %}
{% block title %}db{% endblock %}

{% block content %}
<form method="POST">
<input type="submit" value="show data">
</form>

<!-- Output 1 -->
<p>{{data['names']}}</p>

<!-- Output 2 -->
{% for key, value in data.items() %}
    <p>{{value}}</p>
{% endfor %}


{% endblock %}
Sign up to request clarification or add additional context in comments.

Comments

1

This fixed it for me

db.html

<p>{{data.names}}</p>

main.py

else:
    return render_template("db.html", data = "")

This is to avoid getting the error that "data" is undefined when restarting the server.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.