phpcodeignitermysql-num-rows

Calling PHP's count() on CodeIgniter's num_rows() query result method always returns 1


I have a query like this:

SELECT * FROM configurations WHERE ID = userID

I then have logic like this:

if ($query->num_rows() > 0) {

foreach ($query->result() as $row) { 
    // display data
} else {
    // display no data found message
}

But when I try to do this:

count($query->num_rows())

it is always 1, no matter how many results are returned. If 1 or more are returned the "if" is executed. If there are no results returned the "else" is executed. Yet, the count never changes. What is going on?


Solution

  • You can't count() a number, it works fine. If you only want number of records from table use COUNT() in SQL...

    $sql = mysql_query("SELECT COUNT(0) AS count FROM configurations WHERE ID = userID");
    $sql = mysql_fetch_assoc($sql);
    $count = $sql["count"];
    

    Otherwise just assign $count = $query->num_rows(); as @chriso stated.