Joomla 1.5 Database Functions

Posted by: twmeier

Tagged in: Programming , PHP , Joomla

Sometimes it may be hard to know how to best use Joomla's database class. Here are just a few of the most used database functions.

In Joomla 1.5, include the following line of code inside your php:

<?php
     $database  =& JFactory::getDBO();
?>

Use the $loadObject function when you want to retrieve one row from the database. For example:

$database->setQuery("SELECT * FROM jos_comprofiler WHERE id=125");
$userDetails = $database->loadObject();

You can now access the values as follows:

$userDetails->firstname
$userDetails->lastname
.....

If you want to retrieve more than one row from the database, use the loabObjectList() function. For example:

$database->setQuery("SELECT * FROM jos_comprofiler WHERE id<125");
$userDetails = $database->loadObjectList();

You will now have an array of objects. You can access the values as follows:

$userDetails[0]->firstname
$userDetails[0]->lastname
$userDetails[1]->firstname
$userDetails[1]->lastname
.....

If you want to retrieve a single value from the database, use the loadResult() function. For example:

$database->setQuery("SELECT COUNT(*) FROM jos_comprofiler");
$count= $database->loadResult();

You now have a regular php variable. In this case $count.

There are other Joomla database functions, but these three are the most common.