W
W
Web Building2021-04-01 02:47:29
PHP
Web Building, 2021-04-01 02:47:29

How to write a PHP handler that, from each new user, when clicking on the button, updates the database, increasing the counter by +1 ??

Good day to all! Help please, who has the opportunity?
There is a Jquery-script which in the browser, at each click, executes an increment.
But I need only one single click, from each new user, to be entered into the database, and the total click count on the page is updated. Those. each click increases the total score by +1. The increment should fire only once, from each new user. What should be written in counter.php ??

index.php

<div class="block-up" name="statistics">   
    <form id="ratingsLike" method="post">      
        <button id="btnLike" type="button"><i id="thumbs-up" class="far fa-thumbs-up"></i></button>   
    </form> 
     
    <div class="content-like-dislike">
        <span class="thanks">Thank you very much!</span> 
        <p id="like_count" data-id="<?= $id ?>">0<?= $likes ?></p>    
    </div>
</div>


main.js
$('#btnLike').on('click', function(event) {
  event.preventDefault();

  $.ajax({
    type: "post",
    url: "https://site.com/counter.php",
    data: ("id=" + $("#like_count").attr("data-id")),
    dataType: "text",
    success: function(result) {
      if (result) {
        $("#like_count").text(Number($("#like_count").text()) + 1);
      } else alert("Error");
    }
  });
});


Thank you for attention!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
ZB Venom, 2021-04-01
@zb_venom

Probably the most obvious solution is to store the likes in the likes table:
| id | post_id | user_id | like | , where

  • post_id - post ID,
  • user_id - user ID,
  • like - can be from 0 to 1 or true or false respectively.

And you can't just use the counter.

W
WebEagle, 2021-04-01
@WebEagle

You will need a database, probably you have MySQL and that's good)) + on the server side we start session
We need a session to enter information about the first click there,

if (!isset($_SESSION['is_add_to_db'])) {
// добавление в БД, проверка избавит вас от лишних запросов в БД
}

Table in the database:
userId - or a unique user identifier, if you do not store users in the database in any way - then you can use the UUID or session ID. In any case, this field must be unique
. The remaining fields are optional, according to your desire from your needs. But I would add created dateTime to know when the click happened
How many rows in the table - how many unique clicks

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question