Search code examples
phpcodeigniter-4

How to get specific columns in CodeIgniter 4?


I wanna select specific columns from table. Not all columns.

$this->userModel->where($where)->first();

I'm using this but it returns all data.


Solution

  • According to the CI4 query builder documentation you can use select() in this way:

    $db      = \Config\Database::connect();
    $builder = $db->table('mytablename');        // 'mytablename' is the name of your table
    
    $builder->select('userid, username');       // names of your columns, single string, separated by a comma
    $builder->where('userid', 5);                // where clause
    $query = $builder->get();
    
    return $query;
    

    where() could be possible to use in 4 ways, you can choose.

    This stuff should be placed in Model file, method of which would return $query set of DB data.