Skip to content

Why You Should Always Use Active Record

2010 March 7

I recently came across a post over at Stack Overflow about the pros and cons of using the active record class that CodeIgniter provides. I outlined to the poster several advantages of using the active record class as well as the disadvantages.

Security

Through the development cycle of a web application, you are going to write hundreds if not thousands of queries for each specific thing you want your application to do. That means for each query you write you will have to wrap it with functions that make it safe so that SQL injection and other malicious things cannot take place. Now say if you write 1000 queries through he course of your development and you forget to properly escape them 1% of the time (very very conservative). You will have 10 possible places for your malicious users to bring down your system.

If you had used Active Record you wouldn’t have had that happen. Active Record doesn’t forget to escape and filter those queries. You wouldn’t have a client calling you at 3am because their pride and joy is displaying porn ads or even worse that their customer’s personal information has been leaked to hackers.

Performance

One of his concerns was the performance impact that the Active Record class imposed. Coming from someone who uses the AR class every day in my 9-5, I have never noticed a significant performance impact on any of the queries I write. I dont know the exact benchmarks of it but I would think the most it adds to any query would by around .0001 seconds. I think the small impact it has on your application is well worth the peace of mind that all of your queries are secure from the few malicious users you are bound to cross paths with.

Complex Queries

The Active Record class does a pretty good job at 99% of the queries you are most likely to run. It powers through insert/update/select/delete queries with no problem at all. However it is not perfect. If your application demands a few complex queries you can very easily switch back to straight SQL with $this->db->query(); . This way you get the best of both worlds. You can be secure in your cookie cutter queries that you write all the time but when you have to do something that is a little more complicated you have the ability to switch very easily.

In my opinion there isn’t a real reason not to use CodeIgniter’s Active Record. The benefits it provides far outweigh the downsides. Unless of course your someone who never makes a mistake in programming, in that case forget everything I have told you.

One Response leave one →
  1. April 14, 2010

    hi, nice review about CI active records.
    but, I have a problem that I need to remove automated escape in active record for use some mysql function like FOUND_ROWS(), etc…

    what should I do?

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS