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);
}?>
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Not your answer, but very important: Your code is vulnerable to [SQL Injection](https://stackoverflow.com/questions/332365/how-does-the-sql-injection-from-the-bobby-tables-xkcd-comic-work). Please fix it by using [prepared statements](http://php.net/manual/pt_BR/mysqli.quickstart.prepared-statements.php) – Elias Soares Feb 14 '18 at 20:53

1 Answers1

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612