Counting num_rows issue
I have a query like this:
SELE开发者_如何学PythonCT * 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?
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.
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;
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.
http://us2.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.
精彩评论