Trouble detecting failed $modx->query() in CMP

This code works perfectly on it’s own or in a snippet:

$result = $modx->query("SELECT * from `modx_site_content` WHERE (id = '1' ");
if ($result === false) {
    $modx->log(modX::LOG_LEVEL_ERROR, 'Result is false');
} 

if (! is_object($result)) {
     $modx->log(modX::LOG_LEVEL_ERROR, 'Result is not an object');
}

The $result is not an object and is false.

In my CMP, however, neither case is triggered. The call to $modx->query() appears to return an object containing the query string and nothing else when there are no matches.

Any help appreciated.

Is the missing parenthesis on the second if just a typo in the post?

Also, is isObject a custom function? Because the PHP function is is_object

Also also, the max value for id is ~4.2 billion, so your 9999999999999 would cause a MySQL error.

Yes, the first two are typos and instead of the 999…, I actually used 1 since I have no Resource with that ID.

shouldn’t it be
$result = $modx->query("SELECT * from `modx_site_content` WHERE (id = '1' )");

IIRC, it’s only false if the query is invalid and can’t be prepared. Perhaps when the DB server can’t be reached as well.

In other cases, where the query is valid but simply doesn’t have any results, you’re still going to get an iterable PDOStatement object or array if you were to provide the fetch mode - it’s just going to be empty.

Perhaps checking empty($result) is what you’re looking for?

Thanks Mark,

I should have mentioned that I tried that. It’s not empty, but I did find a workaround since iterating through it produces no results. I just moved the test further down and used if (empty($output)).

Thanks everyone for the help. The docs here are misleading. This example doesn’t work:

$result = $modx->query("SELECT * FROM modx_users WHERE id=1");
if (!is_object($result)) {
   return 'No result!';
}
else {
   $row = $result->fetch(PDO::FETCH_ASSOC);
   return 'Result:' .print_r($row,true);
}