1

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] => anemail@email.com) [1] => Array([mem_id] => 3 [username] => john [email] => anemail2@email.com) [2] => Array([mem_id] => 4 [username] => sam [email] => anemail3@email.com))

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

Andrew S
  • 13
  • 2

1 Answers1

1

$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);

steven7mwesigwa
  • 5,701
  • 3
  • 20
  • 34
  • 1
    You sir are a genius. I didn't know that at all as it's not made clear in the Codeignter documentation. That's solved my issue perfectly. Thanks very much for your answer. – Andrew S Jul 01 '23 at 19:56