Database Table Prefix in CodeIgniter

I must say one of the main reason why I started to look into ActiveRecord for CodeIgniter was the availability to use database table name prefix.

|    ['dbprefix'] You can add an optional prefix, which will be added
|                 to the table name when using the  Active Record class
$db['default']['dbprefix'] = "feed_";

For example: TABLE feed_item

$this->db->get('item');

Many might not know that you can also use it with normal database query using 'swap_pre'. In ./system/application/config/database.php

|    ['dbprefix'] You can add an optional prefix, which will be added
|                 to the table name when using the  Active Record class
$db['default']['dbprefix'] = "feed_";
$db['default']['swap_pre'] = "{PRE}";

So now you can actually use.

$sql = "SELECT * FROM {PRE}item";
$query = $this->db->query($sql);

2 Responses

  1. Kyle on 17 Jul 2009

    Could you explain this and the benefits of it a bit more? Couldn’t you just make the normal db_prefix a pre-defined constant?

    define(‘PRE’,'feed_’);
    $db['default']['dbprefix'] = PRE;

    What’s the special significance of the $db['default']['swap_pre'] item?

    Sorry for the naivity.


    • Zaki on 17 Jul 2009

      It very useful since when you’re using CodeIgniter Database Engine and want to opt out from using it’s ActiveRecord. Using constant however break the CodeIgniter configuration setting where constant should be set in constant.php

      Furthermore it’s bad practice if you want to have multiple database connection (unlikely but still a possible scenario.


Leave your comment