如何使用PHP在提交的表单上打印选中标记图标?

时间:2018-11-25 17:32:44

标签: php if-statement icons submit form-submit

如果<i class="far fa-star"></i>rowCount == 0将打印> 0,则下面的代码将打印出<i class="fas fa-check"></i>,在用户提交表格后,他们将无法除非他们刷新页面,否则请参见<i class="fas fa-check"></i>;在用户提交表单后,页面会自行刷新,并且用户需要再刷新一次才能查看<i class="fas fa-check"></i>

if ($rowCountFav == 0) {
  $favIcon = '<i class="far fa-star"></i>';
}else{$favIcon = '<i class="fas fa-check"></i>';}

if($_SERVER['REQUEST_METHOD'] == 'POST'){
  if(isset($_POST["fav"])){ 
    if ($rowCountFav == 0) {
      $favorito = $conn->prepare("INSERT INTO `favorito` (user_id, nameItem) VALUES (:user_id, :nameItem)");
      $favorito->bindParam(':user_id', $user_id, PDO::PARAM_INT);
      $favorito->bindParam(':nameItem', $nameItem, PDO::PARAM_STR);
      $favorito->execute();
    }
  } 
}
?>
<form action="" method="post" autocomplete="off">
  <button class="btnSub btnA" type="submit" name="fav" />
    Favorito <?= $favIcon;?>
  </button> <span class="ml-1 mr-2">-</span> 
</form> 

我想要的东西:我想在用户提交表单后打印出<i class="fas fa-check"></i>

所以我尝试了这个,但是没有改变:

if($_SERVER['REQUEST_METHOD'] == 'POST'){
  if(isset($_POST["fav"])){ 
    if ($rowCountFav == 0) {
      $favorito = $conn->prepare("INSERT INTO `favorito` (user_id, nameItem) VALUES (:user_id, :nameItem)");
      $favorito->bindParam(':user_id', $user_id, PDO::PARAM_INT);
      $favorito->bindParam(':nameItem', $nameItem, PDO::PARAM_STR);
      $favorito->execute();
    }else{$favIcon = '<i class="fas fa-check"></i>';} ## I just added this line ##
  } 
}

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

您先检查$rowCountFav,然后再进行更新。解决的方法很简单,切换检查和查询。查询后,您还需要更新变量值:

if($_SERVER['REQUEST_METHOD'] == 'POST'){
  if(isset($_POST["fav"])){ 
    if ($rowCountFav == 0) {
      $favorito = $conn->prepare("INSERT INTO `favorito` (user_id, nameItem) VALUES (:user_id, :nameItem)");
      $favorito->bindParam(':user_id', $user_id, PDO::PARAM_INT);
      $favorito->bindParam(':nameItem', $nameItem, PDO::PARAM_STR);
      $favorito->execute();
      $rowCountFav = 1;
    }
  } 
}

if ($rowCountFav == 0) {
  $favIcon = '<i class="far fa-star"></i>';
} else {
  $favIcon = '<i class="fas fa-check"></i>';
}

?>
<form action="" method="post" autocomplete="off">
  <button class="btnSub btnA" type="submit" name="fav" />
    Favorito <?= $favIcon;?>
  </button> <span class="ml-1 mr-2">-</span> 
</form>