Monday 15 December 2014

How to Access Your Joomla Database in an Extension?

Sometimes when you are working on a project you may need to access your Joomla Website's Database to get some extra data for customizing your website.

Joomla API provides functionality to access your database secure and easily.

All you need to do is using JDatabase to access database, select and retrieve the data.


Access Joomla Database in an Extension

For an example, you have a module called mod_yourmodule and you want to print single result at this modules default tmpl file for a specific row (e.g. title of id = $some_value). For an example you want to show the latest entry title from selected table.

Steps you need to follow

Create your function for retrieving the data in module's helper.php
function latestTitle( $some_value ){
// database connection
$db = JFactory::getDbo();
$query = $db->getQuery(true);
// create the query
$query->select('title');
$query->from($db->quoteName('#__mycomponent_table'));
$query->where($db->quoteName('id')." = ".$db->quote($some_value));

$db->setQuery($query);
$result = $db->loadResult();
return $result;
}
Now you can call this function in your modules main php file as below:
// modYourModuleNameHelper is the class name in the helper.php
$latesttitle = modYourModuleNameHelper::latestTitle( $some_value );
You saved the result in $latesttitle

Now you can use this any place of your module's view ( mostly tmpl/default.php )
echo $latesttitle;
That is it!

No comments:

Post a Comment