[英]On clicking a button how to run php script
我是PHP的初學者。 我想將功能添加到喜歡按鈕。 每當用戶單擊“贊”按鈕時,將運行插入查詢以在db中插入值。 主頁上有幾張圖像,必須在product_likes db中插入相應的productimage info(productid)。
<?php
$user_name=$_SESSION['user_name'];
$query="SELECT * FROM product_info";
$result= mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
?>
<div class="w3-container"><br>
<img src="<?php echo "img/product_img/".$row['productimage'].""; ?>">
<p><b>Product Name: </b><?php echo"".$row["productname"].""?><br>
</p>
<form id="like" method="post" action="home1.php">
<button type="submit" name="like"><i class="fa fa-heart"></i> Like</button>
<?php
if(isset($_POST['like'])){
$result=mysqli_query($con,"INSERT INTO product_likes VALUES ('','".$row['productid']."','".$row1['sellerid']."','".$buyerid."')");
}
?>
</form>
</div>
<?php } ?>`
但是每當我運行此產品時,對應於第一張圖片的相同productid,sellerid和Buyerid就會插入數據庫中,並且僅顯示第一張圖片。 有沒有辦法解決這個問題?
您需要了解的第一件事是,PHP是服務器端語言,在客戶端之前執行,而JavaScript是客戶端語言,在服務器端完成處理之后執行,並且沒有返回到服務器。
當您想要做類似基於用戶行為與服務器對話的操作時,您需要配置一個端點並向該服務器發出AJAX調用。 使用jQuery贊帖子的簡單示例是:
$(function() { $("a").click(function(e) { e.preventDefault(); $this = $(this); if ($(this).text().trim() == "Like") { $.post("/posts/like", { PostID: 1 }, function(res) { if (res == "success") $this.text("Unlike"); }); $this.text("Unlike"); } else { if ($(this).text().trim() == "Unlike") { $.post("/posts/unlike", { PostID: 1 }, function(res) { if (res == "success") $this.text("Like"); }); $this.text("Like"); } } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#">Like</a>
上面的示例由於存在后備功能,因此有點“有效”,但這幾乎是概念。 應當單獨給出使“ Like”或“ Unlike”成為可能的整個PHP代碼,並使用jQuery的AJAX函數,將其觸發。
以上兩個URL: /posts/unlike
和/posts/like
接受數據參數PostID
並根據該參數在數據庫中進行必要的更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.