保存每个项目的点击计数 [英] Saving the click counts of an item each item it is clicked

查看:31
本文介绍了保存每个项目的点击计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我尝试为我的网页建立一个赞计数器.
您可以在下面看到点击计数器.完全正常.遗憾的是(但可以肯定)仅用于当前会话...是否有可能永久存储该值?

Currently I try to build up a like counter for my web page.
Below you can see the click counter. It's fully working. Sadly (but for sure) just for the current session... Is there any possibility to store the value forever?

最后一件事!网站上有不止一张图片喜欢.所以我不知道如何使用cookie或localstorage存储值.

One last thing! On the website is more than one picture to like. So I have no Idea how to store the values using cookies or localstorage.

也许您还有其他想法?也许没有JS?

Maybe you have another Idea? Maybe no JS?

var currentValue = 0,
  count = $('.count');

$(document).ready(function() {
  count.each(function(i) {
    $(this).addClass('' + (i += 1));
  });
});



$('.heart').on('click', function(e) {
  var clickElement = $(this).find('.count');

  clickElement.html(parseInt(clickElement.html(), 10) + 1);
});

<p>Click on the Number to increase it by 1</p>

<a class="heart">
  <span class="icon"></span>
  <span class="count">0</span>
</a>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

这是页面上的样子:

推荐答案

您应该做的是将它们存储在数据库中.您应该将ID和该项目的当前计数发送到服务器,通过查询数据库来检查该项目的当前计数和存在,如果已验证,则将其保存到数据库(更新或插入,具体取决于您的DB方案).

What you should do is to store them in a Database. You should send the id and the current count of the item to the server, check the current count and existence of the item by querying database, and if validated, save them to the database (update or insert, depending on your DB Scheme).

已更新

注意:在将值保存到数据库中之前检查其正确性非常重要.因此,通过以 $ _ POST 值发送项目的当前点击数来检查当前点击数是可靠的.实际上,您应该做的只是通过 $ _ POST 发送项目的ID,然后查看该项目是否存在(如果存在),编写以下查询以仅增加一个值来增加点击计数:

Note: It is enormously important to check the values' correctness before saving them into the database. Therefore it is reliable to check current click-count through sending the item's current click-count in a $_POST value. What you indeed should do is to just send the item's id through $_POST and then see if the item exists, if it exists, write the following query to increment the click count just one value:

UPDATE item_table SET (click_counter = click_counter+1) WHERE item_id = ?

这具有几个功能:

  • 它比常规的select + increment_in_php + update速度快得多更快
  • 它使用更少的系统资源
  • 这是最可靠的增量方法,因为在PHP中处理用户值时,另一个请求可能只是更新了该值,因此您在PHP中的价值不是最新鲜的一.但是通过SQL,它已经知道什么是最新值而且不会发生这种碰撞.

如果您将click_counter作为item_table的一列,而您只是对其进行更新,则适用上述方法和说明.但是我有一个建议给你(当然,如果您还没有实现的话)

The above method and explanation apply if you have click_counter as a column of your item_table and you just update it. But I have a recommendation for you (of course if you have not implemented this)

先创建一个表,命名为item_counts,然后再创建三列,例如id,item_id,date_created.您可以添加许多其他列,例如user_ip,user_id(如果已验证)等.

Make a table named, for instance, item_counts and then three columns such as id, item_id, date_created. You may add many other columns such as user_ip, user_id(if authenticated) etc.

然后,每次访问时,您只需在表中添加一条记录即可.与以前的解决方案相比,它具有几个功能:

Then by each visit, you just add a record to your table. This has several features over the previous solution:

  • 它与数据库原子性规则兼容.

  • It is compatible with Database Atomicity rule.

您以后可以对其进行分析.

You can have analytics on it later.

您可以通过查询数据库来获得click_counts:

You get the click_counts by query the datatabase:

SELECT COUNT(id) FROM item_counts WHERE item_id = ?

此解决方案的缺点是,在呈现页面时,您必须有一个额外的查询才能获取项目的click_counts.它当然会占用服务器上更多的空间,但是如果您的项目不是一个很小的项目,那是值得的.但是,如果可以轻松获得良好的实践经验,那么我个人绝不会尝试在项目规模上消灭良好的实践经验.

The disadvantage with this solution is that you have to have an extra query for getting the click_counts of an item when rendering the page. It of course takes more space on the server, but it is worth if your project is not a small-one. However I personally never try to kill good practices for a project's scale, if that practice is easily accessible.

更新后的注释

您可以发送ajax请求:

You can send an ajax request:

var already_clicked = [];

$('.heart').on('click', function(e) {
  var clickElement = $(this).find('.count');
  var itemId = $(this).attr("data-id");
  // changes to current view in the page
  clickElement.html(parseInt(clickElement.html(), 10) + 1);


  // send an ajax request
  $.ajax({
     url : "server.php",
     data : { count : parseInt(clickElement.html(), 10),
            id :  },
     type : "POST",
     success : function(data){
        // do something in the success
     }
  });
});

现在您的PHP脚本应如下所示

Now your PHP script should look like this

// using MySQLi extension
$db = new mysqli("localhost", "usr", "pass", "db");

if( isset($_POST["count"]) && isset($_POST["id"]) )
{
     if (check_if_the_count_is_ok($_POST["count"], $_POST["id"])) 
     {
       $new_count = $_POST["count"] + 1;
       $stmt = $db->prepare("INSERT INTO counts (count, id) VALUES(?, ?)");

       $stmt->bind_param("ii", $new_count, $_POST["id"]);
       $stmt->execute();

       echo json_encode([ "result" : true ]);
     }
     else
     {
      echo json_encode([ "result" : false]);
     }


}


function check_if_the_count_is_ok($item_count, $item_id)
{
     // write a select query to see if the count is true
} 

注意:我假设您单击的项目包含一个名为"data-id"的属性,该属性保存要保存到数据库的项目的ID.

Note: I have assumed your clicked item contains an attribute named "data-id" which holds the id of the item to be saved to the DB.

这篇关于保存每个项目的点击计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆