5

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.

Shashi Roy
  • 323
  • 3
  • 7
  • 22

3 Answers3

8

Following is availab in CI - checkout this page - http://codeigniter.com/user_guide/database/results.html

$query->num_rows()

The number of rows returned by the query. Note: In this example, $query is the variable that the query result object is assigned to:

$query = $this->db->query('SELECT * FROM my_table');

echo $query->num_rows(); 

so that in your example above you need to try

$details->num_rows();
TigerTiger
  • 10,590
  • 15
  • 57
  • 72
  • it does not work in codeigniter when we use Datamapper for DB Query... But if we are working with active record of codeigniter then this is fine. Anyways its really awesome and I am thankful that you took some time out to help me. what Kemal Fadillah has suggested is working perfectly . but time is very precious which you invested to help me out. many many thanks to you for that :) – Shashi Roy May 02 '12 at 10:20
  • 1
    No problem - Shashi - I know you clearly mention datamapper but it just didn't occur to me and post the above for activerecord. Anyway happens... – TigerTiger May 02 '12 at 10:26
6

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.

Kemal Fadillah
  • 9,760
  • 3
  • 45
  • 63
  • perfect... many many many ( infinite times ) thanks to you... :) – Shashi Roy May 02 '12 at 10:15
  • A safer way to count results after the query has run is to use $u->result_count(). This counts the results from $this->_dm_dataset_iterator if its set, else uses count($this->all) instead. – mmmmm Jan 27 '17 at 13:39
1

If the password was encrypted and try again

or if all the data part is fine the try to use the following code

$this->db->where(array('us_email_id' => $username,'us_password' => $password1));
echo $this->db->count_all_results('users');