• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
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
Hi, try using "increment" method:


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

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

#5
(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


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.