CodeIgniter: Preventing row_array() vs row() typo’s?

Twice now I’ve mistakenly used row() instead of row_array() when fetching a single row result. Usually, it goes unchecked without any warning messages. 15-30 minutes later I finally notice the issue; doh doh!

Does anyone have any good suggestions as to ways to prevent this mistake. The object format doesn’t throw a PHP warning, but – of course – the code doesn’t work when you expect an array from a model method.

I accidentally used:

if ($query->num_rows() > 0) {
    return $query->row();
}

Which should instead be:

if ($query->num_rows() > 0) {
    return $query->row_array();
}

I thought about overriding the row() database method and adding in a log_message() statement that would at least let me know (on debug level) that I’m using the object format, instead of the much more typical (for my code) format.

Answer

The only way to “prevent” is pretty much learn over the documentation again so you can keep a common habit of using which function.

You can note yourself, if you are going to return multiple records, use the row_array(), for a singular record, use the row() function.

Remember, don’t speed type your code, proofread your code step by step before continuing.

Overriding the original function is bad practice, using the row() function is useful when retrieving a singular record, so don’t do this.

Leave a Reply

Your email address will not be published. Required fields are marked *