We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Value doubles instead of increasing by +1

I have a value that i need to increment by 1, such as a view count for a blog system. When doing so, the view count is double when inserted into mysql, but printing the before and after results says it's correct.

I noticed a similar topic over here, https://forum.phalcon.io/discussion/13379/value-increments-wrongly-by-2-on-trying-to-update-a-hitcount-but.

My issue works as expected if I disable view rendering, but that isn't exactly "solving" the issue.

echo $post->views;

returns a view count of 0

updating then printing

$post->views++;
echo $post->views;

returns a count of 2

here is the relevant code in relation to the problem at hand:

public function viewAction($slug = null, $page = 1) {
    $post   = BlogPosts::findFirstBySeo_title($slug);

    if (!$post) {
        $this->dispatcher->forward(['controller' => 'errors', 'action' => 'show404']);
        return true;
    }

    $viewcount = $post->views;
    $viewcount += 1;
    echo $post->views;//prints 0(for example)
    $post->views = $viewcount;
    echo $post->views;//prints 1(for example)
    $post->update();
    return true;
}

Thanks in advance to anyone who can share some insight on the issue at hand.

if you do something like this var_dump($post->toArray()) data are equal at you table data?



3.7k

Indeed they are, including the echoing of the values return the expected value.

if you do something like this var_dump($post->toArray()) data are equal at you table data?

I reread your example and I think the problem is that the scalar data is not copied by reference

echo $post->views; // example 13
$viewcount = $post->views;
echo $viewcout; // 13
$viewcount += 1; 
echo $viewcount; //14
echo $post->views; //13
$post->views = $viewcount;
echo $post->views; // 14
if (!$post->update()) {
    var_dump($post->getMessages());
}
echo $viewcount; // 14
echo $post->views; // 14