我的表中有两行名为post。按下按钮后,表会更新上面的行,如果我再次单击它,它会更新应该更新的行。
如果你按下按钮,它会在列中加1。有两行,如果您单击第2行的按钮,它将向第1行添加一行,然后如果您再次单击它,它将更新第2行。或者,如果你按下一个按钮,然后尝试按下另一个按钮,它将更新最后一个你首先单击的按钮,然后更新你想要的按钮。
//The loop echos the row out below
foreach($dbData as $post){
<form method="post" id="liketest" class="redirect" >
<button type="submit" form = "liketest" name="like" value= "'.$post["id"].'">
</button>
</form>
//If you press the button it is supposed to grab the id from the "post" (so the row id) and update count by adding 1
if (isset($_POST['like'])){
$post_id = $_POST['like'];
$result = $conn->query("SELECT * FROM likedpost");
if($result->num_rows == 0) {
$n = "count";
$stmt = $conn->prepare("UPDATE posts SET count = $n+1 WHERE id = $post_id ;");
$stmt->execute();
$stmt->close();
}
}
我希望它会更新您单击的行,但实际结果是它会更新上面的行,然后更新您单击的行。
最佳答案
当有一个循环没有生成动态ID时,就违反了元素ID的唯一性。因此,当您使用form
属性引用另一个表单时,它将不知道要使用哪个表单。只需将form
引用放在按钮上。
在使用准备好的语句时,还应该使用有界占位符。
foreach ($dbData as $post){
echo '<form method="post" class="redirect" >
<button type="submit" name="like" value= "'.$post["id"].'">
Like this post!
</button>
</form>';
}
if (isset($_POST['like'])){
$stmt = $conn->prepare("UPDATE posts SET count = count + 1 WHERE id = ?");
$stmt->bind_param("s", $_POST['like']);
$stmt->execute();
$stmt->close();
}