I have a method that extends the execute() method used in the Drupal 7 database abstraction layer.
When used with db_query, such as:
$result = my_extended_db_query("SELECT * FROM {node} WHERE nid<100")->execute();
$result holds a DatabaseStatementBase object, whether there are resulting rows or not. However, following:
return $result;
the calling function receives an empty array if there had been no query results, instead of a DatabaseStatementBase object. Because of this, ->fetchAll() fails because it is attempting to operate on a non-object.
How do I get my return to arrive as the same object is started as?
The method:
public function execute() {
$sql = $this->sql;
switch ($this->function) {
case 'db_query':
if ($this->args) {
$args = $this->args;
uksort($args,"si_stats_sort_by_length");
foreach($args as $name => $value) {
$sql = str_replace("{" . $name . "}",$value,$sql);
if (is_array($value)) {
$sql = str_replace($name,"('" . implode("', '",$value) . "')",$sql);
} else {
$sql = str_replace($name,"'" . str_replace("'","''",$value) . "'",$sql);
}
}
try {
$query = db_query($sql);
}
catch (Exception $e) {
// log the error
$msg = $e->getMessage() . "\n";
$msg .= $e->getTraceAsString() . "\n";
mylog($msg . PHP_EOL . PHP_EOL . $sql, debug_backtrace(), LOG_ERROR);
}
return $query;
} else {
try {
$query = db_query($sql);
}
catch (Exception $e) {
// log the error
$msg = $e->getMessage() . "\n";
$msg .= $e->getTraceAsString() . "\n";
mylog($msg . PHP_EOL . PHP_EOL . $sql, debug_backtrace(), LOG_ERROR);
}
return $query;
}