I’m trying to make a view counter for my site, but for some odd reason once it counts the first view it doesn’t go up anymore
here is the code
$checkViews = "SELECT COUNT (counter) FROM pageViews WHERE chapterID = '".$_GET["chapterNo"]."'";
$result=getQuery($checkViews,$l);
if($result == 0)
{
$viewupdate = "INSERT INTO pageViews (chapterID, counter) VALUES ('".$_GET["chapterNo"]."', 1)";
$result=getQuery($viewupdate,$l);
}
else if ($result != 0)
{
$viewUpdate = "UPDATE pageViews SET counter = counter++ WHERE chapterID = '".$_GET["chapterNo"]."'";
$result=getQuery($viewUpdate,$l);
}
There’s no ++ operator in MySQL like there is in PHP or C++, so increment that counter value with counter = counter + 1.
If you want to make your code more streamlined, consider UPDATE ON DUPLICATE KEY. This syntax will insert a new value if the key you supply is unique, and updates if the key is already in use:
This inserts 1 as the counter value if you’re inserting a new counter into the database for a chapter on its first view, or else increments the counter by one. You don’t have to do any checking or additional queries.