After working with Nodejs, i got used to various promise-based api's that would throw an exception/error in case of some error.

In both Codeigniter and Laravel, i see that the ALL examples of querying sort of "assume" that everything "will be ok": no try-catch or any other form of error handling.

For instance, i see that CI's "insert" method returns true on success, false on failure. Despite that, none of the examples i've seen, uses any if/else Boolean check on the operation. Same goes for Laravel, which is obviously a much more modern and professional framework.

What i did for now, is to manually check for "true" or "false", for every query that returns a boolean, but the problem is some methods return other types, like the "insert_batch" methods, whose return type is stated as "mixed".

Can someone shed a light on this issue? What approach do others take, to make sure nothing breaks, due to poor database error handling?

A link for the relevant section in CI's docs: https://www.codeigniter.com/user_guide/database/query_builder.html?highlight=query%20builder

1 Answers

3
DFriend On Best Solutions

The "read" queries - get() and get_where() - are not documented correctly. It says the return is a CI_DB_result but it can also return FALSE. I always check the return of the "read" methods using this pattern (or something like it).

$query = $this->db->get();
return $query !== FALSE ? $query->result() : NULL;

The main thing is to know that $query isn't FALSE before trying to run a method on it.

For "write" queries simply returning the result of the Query Builder method works, e.g.

return $this->db->insert('mytable', $data);

Naturally, the receiver of this return needs to pay attention.

The next line of code could return any one of the following: TRUE, FALSE, or a CI_DB_result object.

$this->db->query('YOUR QUERY HERE');

The full definition of query() is

DB_driver::query($sql, $binds = FALSE, $return_object = NULL);

Adjust your return checking to the $sql string request.

Once you nail the query statement syntax down future problems are most often related to bad input data. I usually spend more time checking query input data than output. Things like: Is there actually a value here? Is it the correct data type? Is it in the expected range? Garbage in - Garbage out.