skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.

    $session = ConfigServices::session(); // This line added very top of the code
    if($session->single_view == null){
        $db = ConfigDatabase::connect();
            $builder = $db->table('blog');
            $builder->set('view', 'view+1', FALSE);
            $builder->where('id', $id);
            $builder->update();
              }
    $session->setTempdata('single_view', '1', 5);
    

    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.


  2. Have you tried using type (int) or intval($view) when you get previous value from database?

    $view = "Get previous view value from db";
    $data['view'] = intval($view) + 1;
                    
    $db = ConfigDatabase::connect();
    $builder = $db->table('blog');
    $builder->where('id', $id);
    $builder->update($data);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search