0

I have a loop and submit form. I want to insert one query from a variable but when I click on the submit button last one (id number) variable inserts to the database and when I move $_POST['submit'] part inside the while all ID's insert to the database. How can I insert one of the variables from loop?

This is the while part:

<?php
    $supql="SELECT * FROM `tbl_users_posts`";
    $rez=mysqli_query($conn,$supql);
    while ($row=mysqli_fetch_assoc($rez)) {
        $psid=$row['id'];
        echo $row['post'];
?>
<form id="form1" name="form1" method="post">
  <input type="submit" name="submit" id="submit" value="Submit">
</form>                             
<?php } ?>

And this is the submit part:

if (isset($_POST['submit'])) {
    $pid=$_POST['postid'];
    $inslik="INSERT INTO t_plik (pid,uid)VALUES('$psid','$uid')";
    mysqli_query($conn,$inslik);
}

thanks

<?php
$conn=mysqli_connect('localhost','root','','sitn');mysqli_set_charset($conn,"utf8");
$supql="SELECT * FROM `tbl_users_posts`";
$rez=mysqli_query($conn,$supql);
while ($row=mysqli_fetch_assoc($rez)){
    $psid=$row['id'];
    echo $row['post'];
    ?>
    <form id="form1" name="form1" method="post">
    <input type="hidden" name="postid" value="<?php echo $psid; ?>">
    <input type="submit" name="submit" id="submit" value="Submit">
    </form>                 
    <?php }?>
<?php                                       
if(isset($_POST['submit'])){
    $pid=$_POST['postid'];
    $inslik="INSERT INTO t_plik (pid,uid)VALUES('$psid','$uid') ";
    mysqli_query($conn,$inslik);
}?>
1

1 Answer 1

2

Your form has no input with name="postid", so $_POST['postid'] wasn't being set. You can send this with a hidden input.

<form id="form1" name="form1" method="post">
  <input type="hidden" name="postid" value="<?php echo $psid; ?>">
  <input type="submit" name="submit" id="submit" value="Submit">
</form> 

The form should still be in the while loop, so you'll get a separate form for each post.

You also have a typo in the code that does the inserting:

$pid=$_POST['postid'];

should be:

$psid=$_POST['postid'];

So you weren't inserting the ID that was submitted.

Sign up to request clarification or add additional context in comments.

16 Comments

doesnt change any thing!
It should fix it. Your form has no name="postid", so nothing gets put into $_POST['postid']. This fixes that.
when i click on the submit button, inserts 20-30 query with 12-13-14-15... numbers
I don't see any way that could happen from one submit, unless you have the INSERT in a loop.
I think you need to post more of the script, there's more going on than what you posted.
|

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.