单击按钮如何运行php脚本

时间:2017-06-30 14:42:56

标签: javascript php jquery mysqli php-mysqlidb

我是PHP的初学者。我想将功能添加到喜欢按钮。每当用户单击类似按钮时,将运行插入查询以在db中插入值。主页上有几个图像,必须在product_likes db中插入相应的productimage信息(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时,对应于第一个图像的sellid和buyerid被插入数据库中,只显示第一个图像。有没有办法纠正这个问题?

1 个答案:

答案 0 :(得分:0)

您需要了解的第一件事是,PHP是服务器端语言,在客户端之前执行,JavaScript是客户端语言,在服务器端完成处理后执行,并且没有回到服务器。

当您想要根据用户的行为与服务器说话时,您需要配置一个端点并向服务器发出AJAX调用。使用jQuery来描述帖子的简单示例是:

&#13;
&#13;
$(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");
      }
    }
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#">Like</a>
&#13;
&#13;
&#13;

上面的例子有点&#34;工作&#34;,因为后退,但几乎这是概念。整个PHP代码使&#34; Like&#34;或&#34;与&#34;不同。应该单独给出并使用jQuery的AJAX函数,你需要关闭它。

以上网址:/posts/unlike/posts/like都会接收数据参数PostID,并根据该参数在数据库中进行必要的更改。