Welcome Guest, Not a member yet? Register   Sign In
How to write query on Model and Call Model using Controller in Codeigniter 4?
#1

(This post was last modified: 09-24-2019, 04:50 AM by msjagan.)

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
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
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




Theme © iAndrew 2016 - Forum software by © MyBB