I am working on a forum and got to the point where I want to track page views.
I decided to add the view update code after the mysql query that pulls in the thread contents(OP).
public function get_threads($threadid)
{
$sql = "SELECT t.*, u.username, up.avatar_loc from threads t
INNER JOIN users u
on u.id = t.userid
INNER JOIN user_profiles up
on u.id = up.id
where threadid = $threadid";
$result = $this->db->query($sql)->row_array();
$view = $result['numviews'];
$view ++;
$update = "UPDATE threads SET numviews = $view WHERE threadid = $threadid";
$this->db->query($update);
return $result;
}
However, in Chrome, the numviews
value increases twice upon a page refresh. This doesnt happen in Firefox.
Typically the content will be loaded through an AJAX call, and when it goes through that way, it doesn't have any problems either. After an AJAX call, I use popstate to change the URL, if the user refreshes while on the page, you get the error, or if they navigate to the page (using open in new window).
Here is the controller code for both the AJAX and the non-ajax:
Non-Ajax thread controller:
public function threads($threadid)
{
//...whole lot of other stuff
$data['content'] = $this->components_m->thread($threadid);
$this->load->view('template/template' ,$page);
}
AJAX controller:
public function ajax_thread()
{
$threadid = $this->input->post('threadid');
$result['content'] = $this->components_m->thread($threadid);
echo json_encode($result);
}
Here is components_m->thread($threadid)
public function thread($threadid)
{
$data['threadid'] = $threadid;
$data['wysihtml5_toolbar'] = $this->load->view('newthread/wysihtml5_toolbar','',TRUE);
$data['op'] = $this->threads_m->get_threads($threadid);
$data['replies'] = $this->threads_m->replies($threadid);
$page['subject'] = $data['op']['subject'];
$page['replyTo'] = $this->threads_m->replyTo($data);
$page['replies'] = $this->threads_m->create_replies($data);
return $this->load->view('thread', $page, TRUE);
}
I did a search through my entire project and get_threads($threadid)
only exists in the two functions listed above.
When I use $this->output->enable_profiler(TRUE);
I only see the update function running once.
I even tried commenting out $result['content'] = $this->components_m->thread($threadid);
from ajax_thread()
and it still updates twice in Chrome.
Any thoughts?
Fixed it by changing the UPDATE sql code:
$update = "UPDATE threads SET numviews = numviews + 1 WHERE threadid = $threadid";
$this->db->query($update);