简体   繁体   中英

Flask, SQL, HTML: How to use a variable as a key for INSERT statement

I have a site where users post messages to a wall and reply to messages in comment threads. I can't figure out how to associate comments to messages when the comment form is submitted so that the correct message_id (foreign key) is inserted into the comments table in the database.

I am displaying messages and comments from the database with a for loop in my html, and after each message/comment group there is a form that routes to '/post_comment':

{% for message in messages %}
<div>
    <h3>{{ message['first_name'] }} {{ message['last_name']  }}</h3>
    <h3>{{ message['created_at'] }}</h3>
    <p>{{ message['message'] }}</p>
    {% for comment in comments %}
            {% if message['message_id'] == comment['message_id'] %}
            <p>{{ comment['comment'] }}</p>
            {% endif %}
    {% endfor %}
    <form  class="comments" action="/post_comment" method="POST">
        <h4>Reply</h4>
        <textarea id="post_comment" type="textarea" name="comment"></textarea>
        <input class="submit" type="submit" value="Post">
    </form>
 </div>
{% endfor %}

and the /post_comment route looks like this:

@app.route('/post_comment', methods=['POST'])
def post_comment():
    query = "INSERT INTO comments (user_id, message_id, comment, created_at, updated_at) VALUES (:user_id, :message_id, :comment, NOW(), NOW())"
    data = {
         'user_id': session['id'],
         'message_id': 10,     <<<<<<<<<<<<<<<<<<<<<<<<<<<< WHAT GOES HERE?
         'comment': request.form['comment']
        }
    mysql.query_db(query, data)
    return redirect('/wall')

This all works perfectly fine but as you can see, in the /post_comment route I temporarily hard-coded "message_id' as an integer (10), so every comment is being recorded as a reply to message_id 10. What it actually needs to do is pick up the message_id of the preceding message when its associated comment form is submitted.

How do I let the form know which message it belongs to, and then how do I pass that information on to my query in my route?

It's better if you set message_id as auto increment.

If you can't, get the last ID using MAX and then increase it by 1. It's not the cleanest, but it works. SELECT MAX(message_id) AS last_message_id FROM comments;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM