1

I want to update a query in my index function whenever it open so that i count number of visitor in blog or book in id pages. Here is the simple code which i have written in index function but it increments the value by 10-20 number(not fixed) when ever i refresh the page. I have tried Everything, Debug kit also shows that query is correct. Now i found out it is creating problem because of Inflector::slug('title'), which i have used in url. Please suggest a proper solution.

public function index($id)
{
  $student = TableRegistry::get('count');
  $queryy = $student->query();
  $queryy->update()->set(['temp = temp + 1'])->WHERE(['visitor'=>$id])->execute();
}
Community
  • 1
  • 1
Amit Dangwal
  • 421
  • 1
  • 4
  • 10
  • I have my doubts that the inflector has anything to do with your problem. I guess it's simply that every page view causes a bunch of additional requests, resources, AJAX requests, redirects and the like, sometimes browsers even load URLs twice, Firefox does that when it can't find encoding information in the first x chars. Anyhow, without additional information, nobody here can really help you, as all one can do is guessing, which isn't overly helpful. Please do some debugging and add more details to your question. – ndm Feb 14 '17 at 13:56

1 Answers1

0

I'm not even sure why you are writing your code like that. Here's what I'd do.

$this->loadModel('Students');
$student = $this->Students->find()
    ->where(['id' => $id])
    ->first();
$student->set('temp', (int)$student->get('temp') + 1);
$this->Students->save($student);
David Yell
  • 11,756
  • 13
  • 61
  • 100
  • Possibly because unlike reading, manually incrementing, and saving, such [**`UPDATE` queries are usually atomic**](http://stackoverflow.com/questions/4358732/is-incrementing-a-field-in-mysql-atomic) operations by default. – ndm Feb 14 '17 at 13:50
  • All queries are atomic by default, unless you turn it off. https://github.com/cakephp/cakephp/blob/master/src/ORM/Table.php#L1624-L1625 – David Yell Feb 14 '17 at 14:39
  • 1
    Save operations do by default run in a transaction, yes (don't forget that depending on the isolation level, transactions may be more or less reliable), but your example issues two separate queries, where only the second one runs in a transaction. – ndm Feb 14 '17 at 14:57