【问题标题】:Increment article views on the fly within one row in CodeIgniter在 CodeIgniter 中的一行内动态增加文章视图
【发布时间】:2012-12-18 18:38:55
【问题描述】:

我的表中有一个名为 counter 的列,名为 articles

问题是如何将这一列中的值增加 1 左右,所以在控制器或模型中我将使用 update db 函数。

例如我正在考虑这样的事情:

 $id = 5; //article id (I will get that from the url or db, no problem with that)
 $this->db->update("current counter column value plus one where id column equals $id "); 

假设我获得了文章的浏览量:

$this->db->select_sum("counter")->get("articles");

我知道我需要验证用户的 ip,例如我不是每次页面加载都计算它,而是仅在 5 分钟后计算。不过那是另一回事了 ;)。我只是需要完成这个问题。

【问题讨论】:

    标签: php codeigniter activerecord


    【解决方案1】:

    您可以使用常规查询(带有绑定):

    $sql = "UPDATE articles SET counter = counter + 1 WHERE id = ?";
    $this->db->query($sql, array($id));
    

    或者,使用 AR:

    $query = $this->db->update('articles')
                       ->set('counter','counter+1', FALSE)
                       ->where('id', $id);
    

    set() 中作为第三个参数的 FALSE 告诉它不要转义列名。
    如果只需要递增,则不需要获取查看次数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-06
      • 1970-01-01
      • 1970-01-01
      • 2010-12-22
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多