Search code examples
codeigniter-4

Why is my Codeigniter 4 query build 'select' returning all fields?


I'm new to Codeigniter 4 but very familiar with Codeigniter 3. I'm trying to write a simple DB query to select certain fields from a DB row but the output always contains every field in the table.

Here is my code (model):-

public function test() {

        $db = \Config\Database::connect();
        $builder = $db->table('members');
        $builder->select('mem_id');
        $builder->limit(12, 0);
        if ($builder->countAllResults() > 0) {
            $query = $builder->get();
            $result = $query->getResultArray();
            }
            else
            {
            $result = array();
            }
        return $result;
    
    }//test

I want the above to return just the "mem_id" value but it's returning every field in the row no matter what a put in the select statement. Does anyone know why?

In my controller, I am requesting the output as per:-

public function index()
    {
        $members = new Search;
        $result = $members->test();
        print_r($result); exit();
    }

And the result is:-

Array ([0] => Array([mem_id] => 2 [username] => billy [email] => [email protected]) [1] => Array([mem_id] => 3 [username] => john [email] => [email protected]) [2] => Array([mem_id] => 4 [username] => sam [email] => [email protected]))

The result should just show "mem_id" and not all the other fields. Why is the query returning everything?


Solution

  • $builder->countAllResults()

    Permits you to determine the number of rows in a particular Query Builder query.

    However, this method also resets any field values that you may have passed to select(). If you need to keep them, you can pass false as the first parameter.

    $builder->countAllResults(false);