Welcome Guest, Not a member yet? Register   Sign In
update views+1 doesn't work
#1

I need to update counter views:

In Controller:
PHP Code:
public function show(string $slug)
  
$post $this->findPost($slug);
  if (
$post) {
    
$this->postModel->set('views''views+1')->where('id'$post->id)->update();
    return 
view('blog/post'$data);
  }


In Modal:
PHP Code:
class PostModel extends Model
{
    protected $table 'posts';
    protected $allowedFields = [
        'id',
        'title',
        'lang_id',
        'slug',
        'summary',
        'content',
        'meta_title',
        'meta_keywords',
        'meta_description',
        'reference',
        'reference_link',
        'image',
        'image_caption',
        'image_external_url',
        'post_type',
        'author_id',
        'status',
        'published',
        'visibility',
        'is_slider',
        'is_featured',
        'is_breaking',
        'comments',
        'views',
        'created_by'];
    protected $returnType 'object';
    protected $primaryKey 'id';
    protected $useSoftDeletes true;
    protected $useTimestamps true;


In action views table didn't update and show always 0.

How do can I fix this problem?
Reply
#2

Set the third parameter in the set() method to false.

https://codeigniter.com/user_guide/datab...ating-data

ps: Don't use QueryBuilder in the controller. This is bad practice.
Reply
#3

if I add FALSE I see this error:

Code:
mysqli_sql_exception #1064

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '17:06:21 WHERE `id` = 70' at line 1

you right! my code just for try.

Quote:ps: Don't use QueryBuilder in the controller. This is bad practice.
Reply
#4

(This post was last modified: 01-28-2021, 06:51 AM by nicojmb.)

Hi, try using "increment" method:


PHP Code:
$this->postModel->where('id'$post->id)->increment('views'); 

https://codeigniter.com/user_guide/datab...#increment
Reply
#5

(This post was last modified: 01-30-2021, 12:02 AM by alakian.)

(01-28-2021, 06:50 AM)nicojmb Wrote: Hi, try using "increment" method:


PHP Code:
$this->postModel->where('id'$post->id)->increment('views'); 

https://codeigniter.com/user_guide/datab...#increment

Hello! thanks working now.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB