can you post your code maybe?
$db should always be created during the process that is started by including config.php (which includes lib/setup.php) - and the line you reference is inside get_record_sql - which explicitly does global $db at the start of the function...
unless you're doing something to $db yourself perhaps?
I can't help more than that without you posting your code
General developer forum
Accessing the moodle api from an external file
This discussion has been locked so you can no longer reply to it.