Common Joomla PHP tasks

From Fabrik

Jump to: navigation, search

Databases

The class that manages database operations can be found in
libraries/joomla/database/database/mysql.php
or
libraries/joomla/database/database/mysqli.php
They both have the same methods, but are written to make use of the mySQL and mySQLi database types.

Load an array of rows as objects:
$db =&JFactory::getDBO();
$db->setQuery("SELECT `fieldA`, `fieldB` FROM `tablename` where `fieldC` = 'value'");
$rows = $db->loadObjectList();
But how to return data from this array and display it, e.g when using calc element for this purpose? Let's say we want to display the rows as fieldA fieldB in ordered list. Then we add:
$list = array();
foreach ($rows as $row) {
$list[] = '<li>'.$row->fieldA.' '.$row->fieldB.'</li>';
}
return '<ol>'.implode($list).'</ol>';
Load a single ROW of data as an object:
$db =&JFactory::getDBO();
$db->setQuery("SELECT `fieldA`, `fieldB` FROM `tablename` where `fieldC` = 'value'");
$row = $db->LoadRow();
Load a single VALUE from a ROW of data:
$db =&JFactory::getDBO();
$db->setQuery("SELECT `fieldA` FROM `tablename` where `fieldC` = 'value'");
$fieldA = $db->loadResult();
Note: loading a single row is often used to populate a field with some default data - if you are using eval on a field you should return the value as per this line of code:
return $fieldA;
See using eval for more info

Insert some data into a a database:

$db =&JFactory::getDBO();
$db->setQuery("INSERT INTO `tablename` (`fieldA`, `fieldB`) VALUES ('1', '2')");
$db->query();

Use a Fabrik connection's database, e.g here we are loading the connection whose id is 2:

$cnn = JModel::getInstance('Connection', 'FabrikModel');
$cnn->setId(2);
$db = $cnn->getDb();

In Fabrik3 it is:

$db = FabrikWorker::getDbo(false, 2);

Users

To get the current logged in user in Joomla you need this line

$user =& JFactory::getUser();

The to grab a property from the user object you can do

$userid = $user->get('id');
$name = $user->get('name');
$username = $user->get('username');
$email = $user->get('email');

Dates

Deciding in PHP if a date within an age range

Difference in days between 2 dates in PHP

Personal tools