正在尝试使用PDO添加页面视图


Attempting to add page views using PDO

每次加载网页时,我都会尝试更新页面视图。

每次加载页面时,它都会运行以下函数,但不会向mysql数据库中的post_views行添加1。

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();
    }

我运行的功能简单如下:

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

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

正如你所看到的,我试图在同一个函数中使用两个准备好的语句来a)获得当前的帖子视图数量,然后b)通过添加一个来更新帖子视图,但它根本没有更新。

感谢

您使用的是后缀增量运算符,而不是后缀

$addView = $views++;

这意味着在++递增值之前,您的$addView的值将为$view
将行更改为:

$addView = ++$views;

此外,变量$view包含PDOStatement::fetch(PDO::FETCH_ASSOC)的结果,并且它是具有关键字post_views的数组,因此您应该将代码更改为:

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

或者,如果你想保留一个执行的sql查询,你可以调用这个:

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

不需要调用第一个查询来ge旧值,除非你想对它做一些额外的

代码的另一个注释:
如果希望只有一个结果(page_id告诉我应该只有一个),则不需要使用while循环。

人们似乎不知道后缀和后缀++运算符的区别:

$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