Accessing the database using JDatabase

From Joomla! Documentation

This Namespace has been archived - Please Do Not Edit or Create Pages in this namespace. Pages contain information for a Joomla! version which is no longer supported. It exists only as a historical reference, will not be improved and its content may be incomplete.

This article is for Joomla! CMS Version(s)

Though most of this article still works on 1.5+, some improved ways need to be specified here or in a version specific copy of this article.

Joomla provides a sophisticated database abstraction layer to simplify the usage for third party developers. This guide will help you use this layer.

Why should I use the Joomla database class?

Joomla can use different kinds of SQL database systems and 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 need just two lines of code to get a result from the database in a variety of formats. Using the Joomla database layer ensures a maximum of compatibility and flexibility for your extension.

Preparing the query

// Get a database object$db= JFactory::getDBO();$query="SELECT * FROM #__example_table WHERE id = 999999;";$db->setQuery($query);

First we instantiate the database object; then we prepare the query. You can use the normal SQL syntax. The only thing you have to change is the table prefix. To make this as flexible as possible, Joomla uses a placeholder for the prefix, the “#__”. In the next step, the $db->setQuery(), this string is replaced with the correct prefix.

Now, if we don't want to get information from the database, but rather insert a row into it, we need one more function. Every string value in the SQL syntax should be quoted. For example, MySQL uses backticks `` for names and single quotes ‘‘ for values. Joomla has some functions to do this for us and to ensure code compatibility between different databases. We can pass the names to the function $db->nameQuote($name) and the values to the function $db->Quote($value).

Whatever we want to do, we have to set the query with the $db->setQuery() function. Although you could write the query directly as a parameter for $db->setQuery(), it's commonly done by first saving it in a variable, normally $query, and then handing this variable over. This results in clean, readable code.

setQuery($query)

The setQuery($query) method sets up a database query for later execution either by the query() method or one of the Load result methods.

Notes: The parameter $query must be a valid SQL string. It can either be added as a string parameter or as a variable. Generally a variable is preferred; it leads to more legible code and can help in debugging.

setQuery() also takes three other parameters: $offset, $limit (both used in list pagination) and $prefix, an alternative table prefix. All three variables have default values set and can usually be ignored.

Executing the Query

To execute the query, Joomla provides several functions, which differ in their return value.

Basic Query Execution

query()

The query() method is the basic tool for executing SQL queries on a database. In Joomla it is most often used for updating or administering the database simply because the various load methods detailed on this page have the query step built into them.

Single Row Results

Each of these results functions will return a single record from the database even though there may be several records that meet the criteria that you have set. To get more records you need to call the function again.

Note: Key must be a valid column name from the table; it does not have to be an Index or a Primary Key. But if it does not have a unique value you may not be able to retrieve results reliably.

Miscellaneous Result Set Methods

getNumRows()

getNumRows() will return the number of result rows found by the last query and waiting to be read. To get a result from getNumRows() you have to run it after the query and before you have retrieved any results.

Note: if you run getNumRows() after loadRowList() - or any other retrieval method - you may get a PHP Warning:

Warning: mysql_num_rows(): 80 is not a valid MySQL result resource
in D:\xampp\htdocs\joomla1.5a\libraries\joomla\database\database\mysql.php on line 344

Tips, Tricks & FAQ

Subqueries

Subqueries should be written as follows:

SELECT*FROM#__example WHERE id IN (SELECT id FROM #__example2);

These kinds of queries are supported since MySQL 4.1. If this method fails, you can split the query into two as demonstrated below. Please note that this will (often unnecessarily) increase the load on the database server.

$query="SELECT id FROM #__example2";$database->setQuery($query);$query="SELECT * FROM #__example WHERE id IN (".implode(",",$database->loadResultArray()).")";

Using MySQL User-Defined Variables

MySQL User-Defined Variables are created and maintained for the lifespan of a connection. In Joomla terms this is usually the lifespan of a page request. They can be used in consecutive queries, retaining their value, as long as each query is inside the same connection lifespan.

The first query defines the MySQL User-Defined Variable, the second one increments it by 5, the third one retrieves it's value and will in this case return a value of 5.

The fact that they retain their value can be quite useful, however there is also a little risk. If you use the same User-Defined Variable, in this case @num, in another query, make sure you reset it first. If that other query runs within the same connection lifespan, @num will have remembered its value of 5. You may expect it to start at null or 0.

For details on working with MySQL's User-Defined Variables, please refer to the MySQL documentation at http://dev.mysql.com/doc/

Developer-Friendly Tips

Here is a quick way to do four developer-friendly things at once:

Use a simple constant as an SQL seperator (which can probably be used in many queries).

Make your SQL-in-PHP code easy to read (for yourself and possibly other developers later on).

Have a visibly nice SQL by splitting SQL groups with linebreaks in your error.

$db= JFactory::getDBO();$jAp= JFactory::getApplication();//We define a linebreak constantdefine('L',chr(10));//Here is the most magic$db->setQuery('SELECT * FROM #__table'.L.'WHERE something="something else")'.L.'ORDER BY date desc');$db->query();//display and convert to HTML when SQL errorif(is_null($posts=$db->loadRowList())){$jAp->enqueueMessage(nl2br($db->getErrorMsg()),'error');return;}

See your resulting query

when building an extension, if you want to see the resulting query you can use: