phpmysqlsqlcounterhit

php and mysql hit counter, counting once only


I've tried several methods, but i can only get it to count once. I am thinking there must be something wrong with my database? When i reset my database coloumn "count" to 0, and refresh the page, it counts to 1, but after that no more.

<?php
function update_count() {
    $query = "SELECT `count` FROM `hits`";
    if($query_run = mysql_query($query)) {
        $count++;
        echo $count;
        $query_count = "UPDATE `hits` set `count`='$count'";
        mysql_query($query_count);
    }
}
update_count();
?>

Solution

  • That's because when you refresh the page $count is lost, you need to reselect it from the database:

    $query = "SELECT `count` as cnt FROM `hits`";
    $results = mysql_query($query);
    $count = mysql_fetch_array($result); // take only the first row.
    print_r($count['cnt']);
    

    A simple note, mysql_* functions are deprecated use mysqli_* or prepared statements.