Call to a member function setQuery() on non-object in Joomla

When writing custom queries in Joomla, you might get this error:

Call to a member function setQuery() on non-object

This happens, when you want to execute query using this:

$db->setQuery($your_query);

but haven’t defined $db. Fortunately there is an easy fix. Add this code before setQuery:

$db=JFactory::getDBO();

Example how it looks all together:

$db=JFactory::getDBO();
$db->setQuery($your_query);
$rows = $db->loadObjectList();