Reputation: 158
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);
}?>
Upvotes: 0
Views: 147
Reputation: 781310
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.
Upvotes: 2