dsms21398 2013-08-24 12:44
浏览 7
已采纳

尝试使用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

  • 写回答

1条回答 默认 最新

  • douwei8911 2013-08-24 12:49
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程