Search code examples
codeignitercodeigniter-4

Codeigniter 4 - how to get the first row and the last row of a result


I am trying to get the first row and the last row of a query result. I see from Ci4's docs, there are two methods to help, namley, getFirstRow([$type = 'object']) and getLastRow([$type = 'object']) but I am having difficulty using them. Here is my method so far:

function getLoginFailCount($login_fail_ip, $max_login_attempts = 3, $within_seconds = 320){
    $builder = $this->builder('login_fail');
    $builder->where('login_fail_ip', $login_fail_ip);
    $builder->orderBy('login_fail_created_at','DESC');
    $query = $builder->get(3);
    print_r($query->getFirstRow($query));
}

I get an error at getFirstRow as follows;

Argument 1 passed to CodeIgniter\Database\BaseResult::getFirstRow() must be 
of the type string, object given

How can I get getFirstRow() to work? Doesn't this doc definition say I need to pass it an object? Why does the error say it my be of type string


Solution

  • Well in the documentation for getFirstRow() it states that you can use

    $row = $query->getFirstRow() // which will give you an object
    

    OR

    $row = $query->getFirstRow(‘array’) // which will give you an Array
    

    So your error message, which states...

    Argument 1 passed to CodeIgniter\Database\BaseResult::getFirstRow()
    must be  of the type string, object given
    

    Would make you look and say to yourself, I had better go and read the documentation. So you can either pass in nothing, or a String 'array'.

    So now can you see why

    $query->getFirstRow($query))
    

    does not make any sense! Why would you pass in the $query object as parameter.

    You may have misread the documentation. I see you stated getFirstRow([$type = 'object'])

    You might have got a little confused by that...

    [$type = 'object'] means that the $type is defaulted to be the string 'object' so the returned type is an object by default with No Parameter being passed in.

    If you want it to return an array, then you would specify the string 'array'. So then the $type parameter would be set to the string 'array' and return an array instead of an object.

    Does that help!