2014-01-07 45 views
0

你好,我正在嘗試做一個基於codeigniter框架的帖子計數功能,到目前爲止我所做的工作很棒。該功能是完整的,一切工作正常。Codeigniter帖子查看計數功能 -

但我在這裏有一個問題,從一些專家告訴我,這是函數的正確使用和非上述將損害我的頁面加載。該函數在每次點擊該帖子時都會被jQuery get函數所接受。

首先,我檢查是否有一個IP地址,如果插入的IP地址日期超過24小時,如果它更多,我刪除當前行,然後再次檢查,因爲之前選擇其仍記得最後一個IP地址並以新的datime重新插入。

和其他問題我應該每週做cleanjob或類似的所有ip addreses?

這裏是我的代碼:

function show_count($post_id){ 

     $ip = $this->input->ip_address(); 

      $this->db->select('ip_address,data'); 
      $this->db->from('post_views'); 
      $this->db->where('ip_address',$ip);  
      $query = $this->db->get(); 

       foreach ($query->result() as $row){ 
        $ip_address = $row->ip_address;     
        $data = $row->data;     
       } 

     if(isset($ip_address) && time() >= strtotime($data) + 8640){ 

      $this->db->where('ip_address',$ip); 
      $this->db->delete('post_views'); 
     } 

      $this->db->select('ip_address'); 
      $this->db->from('post_views'); 
      $this->db->where('ip_address',$ip);  
      $query = $this->db->get(); 

       foreach ($query->result() as $row){ 
        $ip_address_new = $row->ip_address;       
       } 

     if(!isset($ip_address_new) && $ip_address_new == false){ 

      $date = new DateTime('now', new DateTimeZone('Europe/Skopje')); 
      $this->db->set('views', 'views+ 1', false); 
      $this->db->where('post_id',$post_id); 
      $this->db->update('posts'); 

      $data = array(
       'ip_address'=>$ip, 
       'data'=>$date->format("Y-m-d H:i:s") 
       ); 

      $this->db->insert('post_views',$data); 
     } 

    } 

謝謝,任何建議將升值。

+0

嘿,我只是想了解你在做什麼更多,你想在他們的閱讀時記錄您的帖子獨特的意見? –

+0

不,我使用發佈視圖計數函數來計算髮布視圖,但在刷新頁面或多次點擊時停止增加視圖值。 – user2317735

+0

好的,讓我建議你在答案中應該做什麼,你描述的是一個獨特的視圖... –

回答

1

如果沒有啓用cookie,則應該使用並設置cookie並設置回退方法,而不是進行大量查詢來增加帖子中的獨特視圖。

$post_id = "???" 
if(isset($_COOKIE['read_articles'])) { 
    //grab the JSON encoded data from the cookie and decode into PHP Array 
    $read_articles = json_decode($_COOKIE['read_articles'], true); 
    if(isset($read_articles[$post_id]) AND $read_articles[$post_id] == 1) { 
    //this post has already been read 
    } else { 

    //increment the post view count by 1 using update queries 

    $read_articles[$post_id] = 1; 
    //set the cookie again with the new article ID set to 1 
    setcookie("read_articles",json_encode($read_articles),time()+60*60*24); 

    } 

} else { 

    //hasn't read an article in 24 hours? 
    //increment the post view count 
    $read_articles = Array(); 
    $read_articles[$post_id] = 1; 
    setcookie("read_articles",json_encode($read_articles),time()+60*60*24);  

} 
+0

好主意。我會嘗試這一個,並會在這裏發佈結果。謝謝哈利 – user2317735

+0

沒問題讓我知道如果你有任何問題:) –

+0

順便說一句,我已經使用cookie登錄系統哈利。這會是一個問題嗎? – user2317735