Feb
12
Joomla - Use loadObjectList and foreach to get list
February 12, 2008 |
Joomla is build to be able to use many different kinds of SQL-database-systems and to run in a variety of environments with different table-prefixes. In addition to these functions, the class automatically creates the database connection. Besides instantiating the object, you only need 2 lines of code to get a result from the database and that in a variety of formats. Using the Joomla database layer ensures a maximum of compatibility and flexibility for your extension.
The database class contains many methods for working with a query’s result set. One of the most useful one would be loadObjectList. The syntax of loadObjectList is: loadObjectList ( $key ), this returns an array of database objects using the current SQL query. Returns false if the query fails. If the $key parameter is set, the array is indexed using the values of the field specified by key. Otherwise, the array is indexed sequentially.
The reason I say this is a really handy function is because we always retrieves a list of results belongs to a certain category. For example, if we want to get all category titles from database jos_categories where section equals to 1, and list them out. This can be done by using the following method:
// Get a database object
$db = JFactory::getDBO();
$query = "SELECT * FROM #__categories
WHERE section = 1";
// Executes the current SQL query string.
$db->setQuery($query);
// returns the array of database objects
$list = $db->loadObjectList();
// create the list of titles
foreach ($list as $item) {
$item_title = $item->title;
echo $item_title.'<br />';
}
Similar Posts
- Way to use Joomla loadAssoc
- Proper Way to Use Joomla getNumRows
- Joomla - Link Excerpt Article Title to Full Article
- Install and Run Joomla on Ubuntu
- Joomla Retrieve Admin Password
- Joomla Manually Setup Enable SEF URL
- Remove Mootools From Joomla Header
- Joomla! - Make Latest News Module Display Date
- Joomla PDF Display Problem in IE7 Fix
- Joomla add Custom User Groups
- Make Joomla localhost Email Work
- Joomla Loads Position Module within Content
Comments
2 Comments so far



















I’d like to know how to get the field names from the rowset. Studying the doc’s has not shown how, basically, load the recordset with loadObjectList from a dynamic statement (unknown number of fields).
Then, I need to loop through the records, from the first to the last fields using $row->field_name (I’ve associated the $row with the record set).
How do I get the fields or, using $row->dataset[0], $row->dataset[1] and so on, but how do I find the number of fields?
Thanks, Gary.
Hi, Gary
Do you think this is what you are looking for?
http://dev.joomla.org/component/option,com_jd-wiki/Itemid,/id,references:joomla.framework:database:jdatabase-getnumrows/