Blog

Creating a Counter using CodeIgniter
Posted on June 26, 2015 in CodeIgniter, MVC, PHP by Matt Jennings

Controller Code Snippet

<?php
        // If counter session variable is set, 
        // increment counter session by one
        if($this->session->userdata('counter'))
        {
            $counter = $this->session->userdata('counter');
            $this->session->set_userdata('counter', $counter + 1);
        }
        // Else, the counter session variable is NOT set,
        // then create it and assign it to 1
        else
        {
            $this->session->set_userdata('counter', 1);
        }
?>

View Code Snippet to Output the Counter Session Variable from the Code Above

<?php
// If the "counter" session variable is set
// echo the code from the controller above which
// increments the variable by 1
if($this->session->userdata('counter'))
{
    echo $this->session->userdata('counter');
}

// Else echo 0
else
{
    echo 0;
}
?>

Leave a Reply