• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to write query on Model and Call Model using Controller in Codeigniter 4?

#1
I am trying to fetch values from users table but throws error. Can anyone give sample snippet for the query (Select, Insert)?

PHP Code:
<?php namespace App\Models;

use 
CodeIgniter\Model;


class 
UserModel extends Model
{
    protected 
$table                  'users';
    protected $primaryKey             'id';

    protected $allowedFields         = ['username''password'];

 
    public function 
all()
    {
        $users_result $this->db->query('SELECT * FROM users')->result_array();

        return 
$users_result;
    }


Please point out what I am doing wrong with the above code
Reply

#2
You don't need to write the SQL query. Use findAll like this:
PHP Code:
public function all()
{
    return $this->asArray()->findAll();



See the this example: https://codeigniter4.github.io/userguide...your-model

Like in CI3, you can return the data as an object or as an array. In CI4 use asArray or asObject:
https://codeigniter4.github.io/userguide...pe-changes
Test your translation files with Translation Tester
Reply

#3
public function all()
{
return $this->asArray()->findAll();
}

this code not working in ci4 please suggest me how to select table data in ci4
Reply

#4
(10-01-2019, 01:18 AM)mohsin khan Wrote: public function all()
{
    return $this->asArray()->findAll();
}

this code not working in ci4 please suggest me how to select table data in ci4

It would be best if you show your model code. Then accurate help may be possible.
Reply

#5
Guys I found way to pass/fetch values between controller and model with hints you provided.

Let me share the sample CRUD system once it is done.


Thanks Guys
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


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