How can I programmatically get the Joomla database prefix using php?

13

3

I sometimes access the Joomla DB via external scripts. The problem I have is that if I ever need to change the prefix, I'll need to edit my scripts again too.

Is there a way to programmatically determine the Joomla database prefix using php? If yes, how?

TryHarder

Posted 2014-04-26T12:25:50.643

Reputation: 1 528

Answers

16

You can get the prefix using the following:

For Joomla 2.5 use:

$app = JFactory::getApplication(); 
$prefix = $app->getCfg('dbprefix');

For Joomla 3.2 use:

$app = JFactory::getApplication(); 
$prefix = $app->get('dbprefix');

But Joomla documentation recommends that you never modify the prefix. I know some backup software allows you to make a change part way through a restore though don't underestimate the work potentially involved.

Source: http://docs.joomla.org/How_to_determine_your_database_prefix

tim.baker

Posted 2014-04-26T12:25:50.643

Reputation: 416

4Joomla Documentation doesn't mean that you must never modify the db_prefix. It just says to not change the value, in the global configuration settings, because this will obviously break the site - by loosing the connection to the database. Changing the value in com_config is not considered a db prefix change, as it doesn't make any changes to the database itself. Database prefix can be changed, assuming someone knows what he is doing. – FFrewin – 2014-04-26T16:12:11.027

4

If you are accessing the Joomla DB via external scripts, maybe you don't want to initialize all joomla stuffs only to get the database prefix. So, you can require the configuration.php file inside your script, instantiate the JConfig class and get the dbprefix

require_once $path_to_joomla_folder . "/configuration.php";
$config = new JConfig;
$dbprefix = $config->dbprefix;

csbenjamin

Posted 2014-04-26T12:25:50.643

Reputation: 657