I want to increase integer value in blog post view. I used this code top of the controller in Codeigniter4:
$db = ConfigDatabase::connect();
$builder = $db->table('blog');
$builder->set('view', 'view+1', FALSE);
$builder->where('id', $id);
$builder->update();
It is updating ..2,4,6,8.. in database instead of 1,2,3,4 while refreshing page. If I use ‘view+2’, updating 2,6,10,14.. But why? Whats wrong with this basic math to compute?
I spent whole day to solve, but not finding any solution.
$view = "Get previous view value from db";
$data['view'] = $view + 1;
$db = ConfigDatabase::connect();
$builder = $db->table('blog');
$builder->where('id', $id);
$builder->update($data);
Getting same result with this query.
2
Answers
The script is running anyway more than once. I've made a temporary solution to run this script once by a trick with computer after thinking too much about my innocent code. I used session Tempdata with 5 second validity timing to run the script once.
At first, the session is null and immediate after the code session is not null, so the script running once, and adding single view nicely.
Have you tried using type (int) or intval($view) when you get previous value from database?