Currently, I have the following PHP code loaded every time the page is refreshed. I am trying to update the views column +1 every time the page is loaded. To do this, I first retrive the previous views value from the table, then run another query to add + to that number. The problem that is occurring is every time I refresh the page, The code somehow adds two instead of 1. So instead of the $viewsA variable increasing by +1, it is increasing by +2.
$query = mysql_query("SELECT * FROM Games WHERE pagename = '$game' ");
WHILE($datarows = mysql_fetch_array($query)):
$title = $datarows['title'];
$description = $datarows['desc'];
$img_url = $datarows['img'];
$cat = $datarows['cat'];
$pagename = $datarows['page'];
$rating = $datarows['rat'];
$viewsA = $datarows['view_count'];
$gameid = $datarows['id'];
endwhile;
$updateviews = $viewsA +1;
mysql_query("UPDATE `trainw_games`.`Games` SET `view_count` = '$updateviews' WHERE `Games`.`id` = $gameid;");
What do I need to change to make it only add +1 to the views column?
I don't think that a while
loop is appropriate for this problem. I would recommend to echo $viewsA . '-' . $updateviews;
to see what the value is before and after the add.
But, why not just run a single UPDATE
statement?
UPDATE Games SET view_count = view_count + 1 WHERE Games.id = $gameid
Of course, you should stop using mysql_
functions and use either MySQLi or PDO:
$stmt = $mysqli->prepare("UPDATE Games SET view_count = view_count + 1 WHERE Games.id = ?");
$stmt->bind_param($gameid);
$stmt->execute();
$stmt->close();
Do you have multiple rows in your database? If yes, it maybe caused by overriding the previous value.
For example:-
If first row the view_count is 1. While the second row view_count is 2.
that overrides the the first row with 2 + 1 = 3 Which makes you thought increased by 2?
UPDATE 1: Ok, try this, put this
$updateviews1 = $viewsA + 1;
if ($viewsA < $updateviews1) { //execute the viewsA + 1 }