M Ray Bell
M Ray Bell

Reputation: 1

PHP page counter script

I am new to php, obviously.. I have created a simple page counter for a webpage to monitor the number of views. I've set up a mySQL database with three columns (id, page, views). and have included the following script on the relative pages, HOWEVER.. instead of increasing the count by 1, it increases it by 2 every time and I have no idea why. Can anyone help?

   <?php
    $page= 'index';

    include('solrx_scripts.php');

    $sql="SELECT * FROM view_log WHERE page = 'index'";
    $result=mysql_query($sql)  or die(mysql_error()); 
    while ($row=mysql_fetch_array($result)){

        $previous = $row['views'];
    }
    $new_count = $previous + 1;

    mysql_query("UPDATE view_log SET views=$new_count WHERE id = 'index'");

    exit;
    ?>

Upvotes: 0

Views: 603

Answers (3)

John Skoubourdis
John Skoubourdis

Reputation: 3259

You just need one line for this :

mysql_query("UPDATE `view_log` SET `views` = `views` + 1 WHERE `id` = 'index'");

and please DON'T use mysql php functions, you will definetly have many problems in the future as it is deprecated

Upvotes: 1

Gustek
Gustek

Reputation: 3760

Make it simply like this no need to select if You always want just add 1

$page= 'index';

include('solrx_scripts.php');

mysql_query("UPDATE view_log SET views=views+1 WHERE id = 'index'");

exit;

If it still increase by 2 it means there is something in solrx_scripts.php or before it.

Upvotes: 1

Rimu Atkinson
Rimu Atkinson

Reputation: 777

Try doing the addition in SQL instead of PHP

mysql_query("UPDATE view_log SET views=views+1 WHERE id = 'index'");

Bear in mind that search engine spiders will cause the view count to be updated also. Something like Google Analytics will give you far more reliable statistics.

Upvotes: 3

Related Questions