How do I insert an post_id into a mysql database

2019-06-12 14:27发布

问题:

I have a comment system that should input an id, an idea_id, a user_id, a comment, the data, and the time. Everything seems to work except every time I post a comment the idea_id is always 0. By the way an idea is basically a post.

I did this using:

<?php
    if(isset($_POST['submit'])) {

        $comment = $_POST['comment'];
        $user_id = $_SESSION['user_id'];
        $idea_id = $_POST['idea_id'];


        if(empty($comment)) {
            $message = "You Haven't Written Anything";
    } else {
        mysql_query("INSERT INTO comments (idea_id, user_id, comment, date, time) VALUES('".$idea_id."', '".$user_id."', '".$comment."', now(), now()) ") or die (mysql_error());
        $message = "OK! Thanks for leaving your comment!";  
        if(isset($_GET['user_id'])) {
    $_SESSION['user_id'] = $_GET['user_id'];
    }

    }   

        echo "<div class = 'box'>$message</div>";
    }
    ?>  



<form method = 'Post'  name = 'comment_form'>

    Comment: <br/>
    <input type = 'text' name = 'comment' id = 'comment' autocomplete= 'off' />
    <input type = 'hidden' name = 'idea_id' value = '<?php echo $idea_id; ?>' />
    <input type = 'submit' name = 'submit' value = 'Comment' /> 
</form> 

回答1:

It doesn't seem like you're keeping a running count of how many ideas are going through your form.

I would suggest you allow the database to manage the idea_id for you and it be a primary key.

How would your application handle duplicate idea_ids?



回答2:

The value for the hidden input should be inside php tags:

<input type = 'hidden' name = 'idea_id' value = '<?php echo $idea_id;?>' />

This way the query won't see the idea_id as a string.

Also as stated by echo_Me you should define the variable somewhere.



回答3:

you should define the $idea_id in your form and then pass it to your form

 $idea_id = "your_idea_id";  
 <input type = 'hidden' name = 'idea_id' value = '<?php echo $idea_id;?>' />

if you wanna see if it works , just try with any number like that

  <input type = 'hidden' name = 'idea_id' value = '66' />