Page 1 of 1

1.5 Pulling Custom Table

Posted: Wed Mar 19, 2008 11:16 pm
by Elis05
I'm an amateur when it comes to Joomla, so please bear with me.

I'm trying to select a field from a custom table I made in Mysql through a module.
However, I've noticed Joomla's PHP commands for pulling tables is fairly...odd (at least to me)

When I try to set a typical code like the below, it (obviously) doesn't work.

Code: Select all

mysql_query("SELECT field FROM table") 
or die(mysql_error());  
I can only assume it's because of how Joomla's set up to operate. I've spent the past four hours on Joomla's site trying to figure this out and I'm ready to slam my head into the keyboard.
I realize that Joomla has designated tables so they appear as "#__table", and have tried searching through the code to find where this is being set but haven't found it, yet.

Can someone explain what it is I'm not understanding or how to select a custom table through a Joomla module?

I'm sorry if my question is on the dumb side, or if this has been addressed before (I did search for a similar question, but didn't find one). Any help would be greatly appreciated. Again, I'm new to Joomla - so please keep answers on the "an idiot could understand this" side.

Re: 1.5 Pulling Custom Table

Posted: Thu Mar 20, 2008 5:34 pm
by radiant_tech
You need to establish a connection with the database. Use the following to accomplish this:

Code: Select all

$db =& JFactory::getDBO();
The next "Joomla!" step would be to create your SQL query

Code: Select all

$query = 'SELECT field FROM tablename";
Often in other components or modules you will see the next line

Code: Select all

$db->setQuery($query);
If your query has included the #__ appended to the tablename, it is replaced with your prefix. The setQuery function can also be passed an offset parameter and a limit parameter for those elements to be added to the query.

And finally, tell the database to return a result. Of course, you can use standard mySQL functions or you can use the J! database functions that are defined in joomla_root/libraries/joomla/database/database/mysql.php (or mysqli.php). As example,

Code: Select all

$result = $db->loadResult();
loads a single value as a result of the query

Code: Select all

$result = $db->loadAssoc();
loads a single row of fields as an associative array

Code: Select all

$result = $db->loadAssocList();
loads a list of rows and their fields as associative arrays