Visit counter resets itself

1

Good morning,

I use a very simple way to count the number of visits I have to different news. Every time you make a request to the news in MySQL I add a visit, and update the entry in the database.

$statement = $conexion->prepare("SELECT * FROM art WHERE id = :id");
$statement->execute(array(':id' => $id));
$posts = $statement->fetch();

$visitas = $posts['visitas'];
$visitas++;

$statement = $conexion->prepare("UPDATE art SET visitas = :visitas WHERE id = $id");
$statement->execute(array(':visitas' => $visitas));

Working works fine, but since February the values have been reset on 3 occasions. The first one gave me the field visits of all the news to 800, the next two times to 0, today is the last time that has happened to me.

Why is it? I do not understand the reason why it happens, the rest of fields are not altered at all.

The field visits in the database is of type int(11) .

    
asked by JetLagFox 22.05.2017 в 16:25
source

1 answer

1

I do not recommend you obtain the value to later increase it. It could be the case of loss of visits: two users who visit the site at the same time, both receive the same current value, both increase it by one and both write the same value in the database, losing one of them.

I recommend you obtain the current value after updating it as follows:

/* Primero incrementamos el valor de las visitas */
$statement = $conexion->prepare('
  UPDATE art SET visitas = visitas + 1 WHERE id = :id
');
$statement->execute([
  ':id' => $id]
);

/* Ahora obtenemos el contador para mostrarlo */
$statement = $conexion->prepare('
  SELECT *
  FROM art
  WHERE id = :id
');
$statement->execute([':id' => $id]);
$posts = $statement->fetch();

$visitas = $posts['visitas'];

Updates of type SET visitas = visitas + 1 are executed atomic, so no visit to the page will be lost and there is no possibility of resetting unless it reaches the capacity limit of the type of field used to store the number of visits.

    
answered by 22.05.2017 / 17:12
source