My SQL always adds 24 clicks to each access instead of 1

0

I have a script that counts the visits on my web pages and stores mysql, however, it is adding 24 clicks to each access, instead of 1 .

What's wrong with this code?

See the script:

<?php
$idcategoria = 19;
     if (!empty($idcategoria)){
         $guiacomercial_cliques=mysqli_query($con,"Select cliques FROM 
         cliquesguia WHERE categoria =".$idcategoria);
         if (mysqli_num_rows($guiacomercial_cliques) > 0){
              $painel=mysqli_query($con,"UPDATE cliquesguia SET cliques = 
              (cliques + 1) where categoria =".$idcategoria);
         }else{
            $painel=mysqli_query($con,"INSERT INTO cliquesguia (categoria, 
            cliques) VALUES (".$idcategoria.", '1')");
         }
     }
?>
    
asked by anonymous 25.07.2017 / 19:45

1 answer

0

Just try this, without the while:

<?php
     if (!empty($idcategoria)){
         $guiacomercial_cliques=mysqli_query($con,"Select cliques FROM 
         cliquesgc WHERE categoria =".$idcategoria);
         if (mysqli_num_rows($guiacomercial_cliques) > 0){
              $painel=mysqli_query($con,"UPDATE cliquesgc SET cliques = 
              (cliques + 1) where categoria =".$idcategoria);
         }else{
            $painel=mysqli_query($con,"INSERT INTO cliquesgc (categoria, 
            cliques) VALUES (".$idcategoria.", '1')");
         }
     }
?>

Notes if $idcategoria is an integer, there is no need to use quotation marks. They are used only for string (text).

I could still improve with the ON DUPLICATED KEY UPDATE clause, leaving much leaner and leaner code. I'll leave a working example below:

If category is the primary key (PK) of your table could do just that:

<?php
     if (!empty($idcategoria)){
            $painel=mysqli_query($con,"INSERT INTO cliquesgc (categoria, 
            cliques) VALUES (".$idcategoria.", '1') ON DUPLICATE KEY UPDATE 
            cliques=(cliques+1);");
     }
?> 
  

Translating, insert in the cliquesgc table if there is no category entered ( which should be the primary key ), otherwise the category already exists ( Key is Duplicate >) add +1 to the clicks field.

    
25.07.2017 / 19:56