andreaem
andreaem

Reputation: 1655

PHP MySQL article views count not working

In my blog, I want to count the articles views every time the page is loaded so I can make a chart of the top articles.

I'm using this code but something goes wrong.

If I put the first query in phpMyAdmin the query result is correct.

$readViewsCountSQL = "SELECT `view_count` FROM `andreaem`.`article` WHERE `article`.`slug` = '$articleSlug' LIMIT 1";
$readViewsCount = $DB_CON ->query($readViewsCountSQL); 
$readViewsCountResult = $readViewsCount->fetch(PDO::FETCH_ASSOC);

function updateVCount ($current) {
    $count = $current ++;
    return $count;
}
$addViewsCount = updateVCount($readViewsCountResult);
var_dump($addViewsCount); //This return the correct value
$updateViewsCount = "UPDATE `andreaem`.`article` SET  `view_count` =  '$addViewsCount' WHERE  `article`.`slug` = '$articleSlug'";
$DB_CON ->query($updateViewsCount);

In the mySQL logs the query was executed successfully but something goes wrong.

$DB_CON is the PDO connection and working in other queries

Upvotes: 0

Views: 144

Answers (1)

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

Taken straight from the comment,

You don't need that SELECT query, you can do everything in just one simple query,

$updateViewsCount = "UPDATE andreaem.article SET view_count = view_count+1 WHERE article.slug = '$articleSlug'";

Upvotes: 2

Related Questions