我已经实现了 LIKE 功能,但只有表中的最后一条记录得到更新,无论用户单击哪一行的 LIKE 按钮。
我在此处和其他地方查看了与此类似的其他问题,并尝试了建议的补救措施,但没有任何效果。任何帮助表示赞赏!
这将输出表格,其中有一列用于 LIKE 按钮:
<table class="table table-bordered">
<tr>
<th>Word ID</th>
<th>User ID</th>
<th>User Name</th>
<th>Word</th>
<th>Meaning</th>
<th>Example</th>
<th>Likes</th>
</tr>';
foreach ($data as $row)
{
echo '<tr>';
foreach ($row as $value)
{
echo '<td>';
echo $value;
echo '</td>';
}
echo '<td>
<form method="POST" action="'.$_SERVER["PHP_SELF"].'">
<input type="hidden" name="LIKE" value="'.$row['wordID'].'">
<input id="'.$row['wordID'].'" type="submit" class="btn btn-success" value="LIKE">
</form>
</td>';
echo '</tr>';
}
echo '</table>';
我的更新代码是:
if($_POST['submit'])
{
$sql = "UPDATE vocab SET likes = likes+1 where wordID = '{$row['wordID']}'";
$stmt = $db->prepare($sql);
我已经尝试了所有方法,包括添加这样的 javascript 来获取更新代码所需的 ID。没有运气!
echo '<script type="text/javascript">
function submitForm(){
var selectButton = document.getElementById( "'.$row['wordID'].'" );
selectButton.click();
}
</script>';
选项1:我会改变:
<input name="like" value="'.$row['wordID'].'"
type="submit" class="btn btn-success">
并且:
if (!empty($_POST['like'])) {
$sql = "UPDATE vocab SET likes = likes+1 where wordID = '".$_POST['like']."'";
$stmt = $db->prepare($sql);
...
选项 2:要将 like 显示为按钮值,请尝试以下操作:
<input name="like['.$row['wordID'].']" value="LIKE"
type="submit" class="btn btn-success">
并在 php 文件中:
if (!empty($_POST['like'])) {
foreach ($_POST['like'] as $key => $value) {
$sql = "UPDATE vocab SET likes = likes+1 where wordID = '".$key."'";
$stmt = $db->prepare($sql);
...
}
}
选项 3:
<input name="like_'.$row['wordID'].'" value="LIKE"
type="submit" class="btn btn-success">
和:
if (!empty($_POST)) {
foreach($_POST as $key => $value) {
if (substr($key, 0, 5) == 'like_') {
$sql = "UPDATE vocab SET likes = likes+1 where wordID = '".substr($key, 5)."'";
$stmt = $db->prepare($sql);
...
但要小心 SQL 注入。在执行查询或使用参数执行准备好的查询之前,您应该清理 $_POST['like'] 值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句