sehummel
sehummel

Reputation: 5568

Counting num_rows issue

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?

Upvotes: 0

Views: 1153

Answers (3)

Dejan Marjanović
Dejan Marjanović

Reputation: 19380

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.

Upvotes: 1

Dan Spiteri
Dan Spiteri

Reputation: 1819

You're getting an integer with $query->num_rows(), so when you run that integer through the count() function it is designed to return 1.

https://www.php.net/manual/en/function.count.php

If var is not an array or an object with implemented Countable interface, 1 will be returned. There is one exception, if var is NULL, 0 will be returned.

Upvotes: 1

chriso
chriso

Reputation: 2552

Firstly else { should be } else { - you're missing a brace

Secondly, count() is used to count the number of elements in an array. Since $query->num_rows() returns a number rather than an array, you don't need to use count(). In your case, count() was telling you that there's one number, not what the actual number was!

Try:

$count = $query->num_rows();
echo $count;

Upvotes: 1

Related Questions