phpcodeigniterdatamappercodeigniter-2codeigniter-datamapper

how to count the number of rows returned by query in Codeigniter with Datamapper


I am using the following query in controller of codeigniter.

    $u -> where('us_email_id', $username);
    $u -> where('us_password', $password1);
    $details = $u -> get();
    $total = count($details);
    echo $total; echo "<br>";
    echo count($details);

In the above code "$u" is the object name for the class "User" for the datamapper "User" where the table name in my database is "users". I want to see how many rows are returned after executing the query. "$total" always displays 1 even if userid and password is not matched. What I want is , if number of rows returned 1 then "ok" else "something wrong". I know its basic but if somebody know it then please help me out. Thanks in advance.


Solution

  • If you just want to count the total rows found, call the count() method instead of get().

    $u->where('us_email_id', $username);
    $u->where('us_password', $password1);
    $total = $u->count();
    

    But, if you also need the data, then you can simply call get(), and after that use PHP count() to count how many elements are there inside the all property of the object.

    $u->where('us_email_id', $username);
    $u->where('us_password', $password1);
    $u->get();
    $total = count($u->all);
    

    You can check out the documentation for more details.