'Try/catch 'Call to a member function query() on null' error

I have a SQL query ($query) that I create dynamically based on a users selections (I already perform sanitizing on user input so there is no issue of SQL injection). However sometimes the query returns a PHP Fatal error so I wanted to output all of the variables to a file so do some digging.

My code is:

try {
    $results = $db->query($query);
} catch (Exception $e) {
    $all_vars = get_defined_vars();
    file_put_contents('query_problems.txt',date('Y-m-d H:i:s') . print_r($all_vars, True),FILE_APPEND);
}

However I still receive an error

Uncaught Error: Call to a member function query() on null

and the line it points to is where I run $db->query($query).

What am I doing wrong? How do I catch this error?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source