Home php mysql - insert one query from a while loop
Reply: 1

php mysql - insert one query from a while loop

behzad
1#
behzad Published in 2018-02-14 19:24:09Z

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
2#
Barmar Reply to 2018-02-14 21:14:23Z

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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.482879 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO