$collection->count() works locally but not at the staging server

I’m using $collection->count() and in my local environment it works just fine. But when I’m testing the site on a staging server I get this error message: Error thrown with message "Call to a member function count() on boolean"

Code snippet from the template

    <? foreach(page('servicesystem/arenden')->children() as $item): ?>
        <li class="c-sidebarNav-item <?= r($item->isOpen(), 'is-active') ?>">
            <a class="c-sidebarNav-link" href="<?= $item->url() ?>"><?= $item->title()->html() ?></a>

            <? if($item->uid() == 'nya'): ?>
                <? if($tasks->count() > 0): ?>
                    <div class="c-sidebarNav-counter">
                        <?= $tasks->count() ?>
                    </div>
                <? endif ?>
            <? endif ?>
        </li>
    <? endforeach ?>

The debugger stops here: <? if($tasks->count() > 0): ?>

I get my tasks from this snippet: <? $tasks = db::select('tasks', '*', array('status' => 1), 'created desc'); ?>

My environment (local and staging):

  • PHP 7.1
  • Kirby version: 2.4.0 beta 2

What does $tasks return if you do a var_dump($tasks) (probably null or false, otherwise you would not get the message). Why are you using a beta version of Kirby?

It returns the data from the database. I have just forgot to update from beta. I’ll do that.

object(Collection)#161 (1) {
  [0]=>
  object(Obj)#162 (14) {
    ["id"]=>
    int(5)
    ["firstname"]=>
    string(7) "Mattias"
    ["lastname"]=>
    string(4) "Rydh"
    ["personalcode"]=>
    string(11) "771002-2455"
    ["email"]=>
    string(27) "mattias.rydh@grandpublic.se"
    ["phone"]=>
    string(8) "98765436"
    ["address"]=>
    string(9) "kljhfgdfg"
    ["created"]=>
    string(19) "2016-11-17 08:48:53"
    ["updated"]=>
    string(19) "2016-11-29 15:53:10"
    ["task"]=>
    string(3) "Hje"
    ["comment"]=>
    string(29) "Ringer kunden. Allt är fixat"
    ["status"]=>
    int(1)
    ["key"]=>
    int(1)
    ["handler"]=>
    string(12) "Mattias Haal"
  }
}

var_dump($tasks->count()) returns int(1).

But only locally, not on the remote server?

It returns false on the remote server, thus something wrong with the db-connection?

I guess that the db-connection does not work as it should, yes.

To prevent such errors, it is recommended to check if the object exists before calling a method on it:

<?php
if($tasks) {
// do something
}
?>

(That is a general rule for all sorts of objects)

Strangely, I have not changed the database and it worked in the past. I know that the information to the database is correct.

Thanks for the advice, I’ll do that.