尝试使用PDO添加页面视图

I am attempting to update page views ever time a webpage is loaded.

Every time the page loads it runs the following function, but it doesn't add 1 to the post_views row in the mysql database.

function addPostView($post_id, $dbh){

        $stmt = $dbh->prepare('SELECT post_views FROM crm_posts WHERE post_id=?');
        $stmt->bindValue(1, $post_id);
        $stmt->execute();

        while($views = $stmt->fetch(PDO::FETCH_ASSOC)) {

                $addView = $views++;
        }

        $stmt2 = $dbh->prepare('UPDATE crm_posts SET post_views=? WHERE post_id=?');
        $stmt2->bindValue(1, $addView);
        $stmt2->bindValue(2, $post_id);
        $stmt2->execute();

    }

I am running the function simply as follows:

if(isset($_GET['post_id']) && checkPostID($_GET['post_id'], $dbh)!= 0){


        $post_id = $_GET['post_id'];
        addPostView($post_id, $dbh);
...

As you can see I am attempting to use two prepared statements in the same function to a) get the current number of post views and then b) update the post views by adding one, but it isn't updating at all.

Thanks

You are using postfix increment operator instead of suffix:

$addView = $views++;

This means your $addView will have value of $view before ++ increments the value.
Change the line to:

$addView = ++$views;

Also variable $view contains result of PDOStatement::fetch(PDO::FETCH_ASSOC) and it is an array with key post_views so you should change the code to:

$addView = ++$views['post_views'];

Or if you want to spare one sql query executed you can just call this:

$stmt2 = $dbh->prepare('UPDATE crm_posts SET post_views=post_views+1 WHERE post_id=?');
$stmt2->bindValue(1, $post_id);
$stmt2->execute();

No need to call first query to ge the old value unless you want to do something extra with it

Another note to your code:
You do not need to use while loop if you expect to have only one result (page_id tells me it should be only one).

It seems that people don't know the difference between postfix and suffix ++ operator:

$view = 0;
$addView = $view++; // $addView = 0, $view = 1, since ++ is executed after value of $view has been assigned to $addView

$view = 0;
$addView = ++$view; // $view = 1; $addView = 1, since $view is first incremented then assigned to $addView