Actions

Difference between revisions of "Selecting data using JDatabase"

From Joomla! Documentation

m (Wilsonge moved page User:Selecting data using JDatabase to Selecting data using JDatabase without leaving a redirect)
(Selecting Records from Multiple Tables)
(21 intermediate revisions by 8 users not shown)
Line 1: Line 1:
 
{{version|2.5,3.x}}
 
{{version|2.5,3.x}}
{{dablink|'''Version Note:''' While this document pertains to Joomla! 2.5 and 3.x, <code>$db->execute()</code> does not exist in Joomla 2.5. In that case, change <code>$db->execute()</code> to <code>$db->query()</code>. Using <code>$db->query()</code> is possible in Joomla 3.x but will generate a deprecated notice.}}
+
{{dablink|'''Version Note:''' While this document pertains to Joomla! 2.5 and 3.x, <code>$db->query()</code> throws a deprecated notice in Joomla 3.0+. In that case, change <code>$db->query()</code> to <code>$db->execute()</code>. However note <code>$db->execute()</code> does not work in Joomla 2.5.}}
  
 
This tutorial is split into two independent parts:
 
This tutorial is split into two independent parts:
* Inserting, updating and removing data from the database. It also touches on transactions.
+
* Inserting, updating and removing data from the database.
* Selecting data from a table and retrieving it in a variety of different forms
+
* Selecting data from one or more tables and retrieving it in a variety of different forms
  
This section of the documentation looks at selecting data from a database table and retrieving it in a variety of formats. To see the other part [[User:Wilsonge/Inserting,_Updating_and_Removing_data_using_JDatabase|click here]]
+
This section of the documentation looks at selecting data from a database table and retrieving it in a variety of formats. To see the other part [[Inserting,_Updating_and_Removing_data_using_JDatabase|click here]]
  
 
== Introduction==
 
== Introduction==
Line 46: Line 46:
 
// Select all records from the user profile table where key begins with "custom.".
 
// Select all records from the user profile table where key begins with "custom.".
 
// Order it by the ordering field.
 
// Order it by the ordering field.
$query->select(array('user_id', 'profile_key', 'profile_value', 'ordering'));
+
$query->select($db->quoteName(array('user_id', 'profile_key', 'profile_value', 'ordering')));
$query->from('#__user_profiles');
+
$query->from($db->quoteName('#__user_profiles'));
$query->where('profile_key LIKE \'custom.%\'');
+
$query->where($db->quoteName('profile_key') . ' LIKE '. $db->quote('\'custom.%\''));
 
$query->order('ordering ASC');
 
$query->order('ordering ASC');
  
Line 62: Line 62:
 
<source lang="php">
 
<source lang="php">
 
$query
 
$query
     ->select(array('user_id', 'profile_key', 'profile_value', 'ordering'))
+
     ->select($db->quoteName(array('user_id', 'profile_key', 'profile_value', 'ordering')))
     ->from('#__user_profiles')
+
     ->from($db->quoteName('#__user_profiles'))
     ->where('profile_key LIKE \'custom.%\'')
+
     ->where($db->quoteName('profile_key') . ' LIKE '. $db->quote('\'custom.%\''))
 
     ->order('ordering ASC');
 
     ->order('ordering ASC');
 
</source>
 
</source>
  
 
Chaining can become useful when queries become longer and more complex.
 
Chaining can become useful when queries become longer and more complex.
 +
 +
Grouping can be achieved simply too.  The following query would count the number of articles in each category
 +
<source lang="php">
 +
$query
 +
    ->select( array('catid', 'COUNT(*)') )
 +
    ->from($db->quoteName('#__content'))
 +
    ->group($db->quoteName('catid'));
 +
</source>
  
 
==Selecting Records from Multiple Tables==
 
==Selecting Records from Multiple Tables==
Line 83: Line 91:
 
// Select all articles for users who have a username which starts with 'a'.
 
// Select all articles for users who have a username which starts with 'a'.
 
// Order it by the created date.
 
// Order it by the created date.
 +
// Note by putting 'a' as a second parameter will generate `#__content` AS `a`
 
$query
 
$query
     ->select(array('a.*', 'b.username', 'b.name'))
+
     ->select($db->quoteName(array('a.*', 'b.username', 'b.name')))
     ->from('#__content AS a')
+
     ->from($db->quoteName('#__content', 'a'))
     ->join('INNER', '#__users AS b ON (a.created_by = b.id)')
+
     ->join('INNER', $db->quoteName('#__users', 'b') . ' ON (' . $db->quoteName('a.created_by') . ' = ' . $db->quoteName('b.id') . ')')
     ->where('b.username LIKE \'a%\'')
+
     ->where($db->quoteName('b.username') . ' LIKE \'a%\'')
     ->order('a.created DESC');
+
     ->order($db->quoteName('a.created') . ' DESC');
  
 
// Reset the query using our newly populated query object.
 
// Reset the query using our newly populated query object.
Line 97: Line 106:
 
</source>
 
</source>
  
The join method above enables us to query both the content and user tables, retrieving articles with their author details. There are also convenience methods for [http://api.joomla.org/Joomla-Platform/Database/JDatabaseQuery.html#innerJoin inner], [http://api.joomla.org/Joomla-Platform/Database/JDatabaseQuery.html#leftJoin left], [http://api.joomla.org/Joomla-Platform/Database/JDatabaseQuery.html#rightJoin right] and [http://api.joomla.org/Joomla-Platform/Database/JDatabaseQuery.html#outerJoin outer] joins.
+
The join method above enables us to query both the content and user tables, retrieving articles with their author details. There are also convenience methods for joins:
 +
* [http://api.joomla.org/Joomla-Platform/Database/JDatabaseQuery.html#innerJoin innerJoin()]
 +
* [http://api.joomla.org/Joomla-Platform/Database/JDatabaseQuery.html#leftJoin leftJoin()]
 +
* [http://api.joomla.org/Joomla-Platform/Database/JDatabaseQuery.html#rightJoin rightJoin()]  
 +
* [http://api.joomla.org/Joomla-Platform/Database/JDatabaseQuery.html#outerJoin outerJoin()]
  
 
We can use multiple joins to query across more than two tables:
 
We can use multiple joins to query across more than two tables:
Line 103: Line 116:
 
<source lang="php">
 
<source lang="php">
 
$query
 
$query
     ->select(array('a.*', 'b.username', 'b.name', 'c.*', 'd.*'))
+
     ->select($db->quoteName(array('a.*', 'b.username', 'b.name', 'c.*', 'd.*')))
     ->from('#__content AS a')
+
     ->from($db->quoteName('#__content', 'a'))
     ->join('INNER', '#__users AS b ON (a.created_by = b.id)')
+
     ->join('INNER', $db->quoteName('#__users', 'b') . ' ON (' . $db->quoteName('a.created_by') . ' = ' . $db->quoteName('b.id') . ')')
     ->join('LEFT', '#__user_profiles AS c ON (b.id = c.user_id)')
+
     ->join('LEFT', $db->quoteName('#__user_profiles', 'c') . ' ON (' . $db->quoteName('b.id') . ' = ' . $db->quoteName('c.user_id') . ')')
     ->join('RIGHT', '#__categories AS d ON (a.catid = d.id)')
+
     ->join('RIGHT', $db->quoteName('#__categories', 'd') . ' ON (' . $db->quoteName('a.catid') . ' = ' . $db->quoteName('d.id') . ')')
     ->where('b.username LIKE \'a%\'')
+
     ->where($db->quoteName('b.username') . ' LIKE \'a%\'')
     ->order('a.created DESC');
+
     ->order($db->quoteName('a.created') . ' DESC');
 
</source>
 
</source>
  
 
Notice how chaining makes the source code much more readable for these longer queries.
 
Notice how chaining makes the source code much more readable for these longer queries.
 +
 +
In some cases, you will also need to use the AS clause when selecting items to avoid column name conflicts. In this case, multiple select statements can be chained in conjunction with using the second parameter of $db->quoteName.
 +
 +
<source lang="php">
 +
$query
 +
    ->select($db->quoteName('a.*'))
 +
    ->select($db->quoteName('b.username', 'username'))
 +
    ->select($db->quoteName('b.name', 'name'))
 +
    ->from($db->quoteName('#__content', 'a'))
 +
    ->join('INNER', $db->quoteName('#__users', 'b') . ' ON (' . $db->quoteName('a.created_by') . ' = ' . $db->quoteName('b.id') . ')')
 +
    ->where($db->quoteName('b.username') . ' LIKE \'a%\'')
 +
    ->order($db->quoteName('a.created') . ' DESC');
 +
</source>
 +
 +
A second array can also be used as the second parameter of the select statement to populate the values of the AS clause. Remember to include nulls in the second array to correspond to columns in the first array that you don't want to use the AS clause for:
 +
 +
<source lang="php">
 +
$query
 +
    ->select($db->quoteName(array('a.*', 'b.username', 'b.name'), array('', 'username', 'name'))
 +
    ->from($db->quoteName('#__content', 'a'))
 +
    ->join('INNER', $db->quoteName('#__users', 'b') . ' ON (' . $db->quoteName('a.created_by') . ' = ' . $db->quoteName('b.id') . ')')
 +
    ->where($db->quoteName('b.username') . ' LIKE \'a%\'')
 +
    ->order($db->quoteName('a.created') . ' DESC');
 +
</source>
  
 
==Query Results ==
 
==Query Results ==
Line 137: Line 174:
 
$query = $db->getQuery(true);
 
$query = $db->getQuery(true);
 
$query->select('COUNT(*)');
 
$query->select('COUNT(*)');
$query->from('#__my_table');
+
$query->from($db->quoteName('#__my_table'));
$query->where($db->nameQuote('name')." = ".$db->quote($value));
+
$query->where($db->quoteName('name')." = ".$db->quote($value));
  
 
// Reset the query using our newly populated query object.
 
// Reset the query using our newly populated query object.
Line 149: Line 186:
 
$query = $db->getQuery(true);
 
$query = $db->getQuery(true);
 
$query->select('field_name');
 
$query->select('field_name');
$query->from('#__my_table');
+
$query->from($db->quoteName('#__my_table'));
$query->where($db->nameQuote('some_name')." = ".$db->quote($some_value));
+
$query->where($db->quoteName('some_name')." = ".$db->quote($some_value));
  
 
$db->setQuery($query);
 
$db->setQuery($query);
Line 416: Line 453:
 
<pre>Warning: mysql_num_rows(): 80 is not a valid MySQL result resource  
 
<pre>Warning: mysql_num_rows(): 80 is not a valid MySQL result resource  
 
in libraries\joomla\database\database\mysql.php on line 344</pre>
 
in libraries\joomla\database\database\mysql.php on line 344</pre>
 +
 +
[[Category:Extension development]]
 +
[[Category:Database]]
 +
[[Category:JFactory]]

Revision as of 08:33, 3 April 2014

This tutorial is split into two independent parts:

  • Inserting, updating and removing data from the database.
  • Selecting data from one or more tables and retrieving it in a variety of different forms

This section of the documentation looks at selecting data from a database table and retrieving it in a variety of formats. To see the other part click here

Contents

Introduction

Joomla provides a sophisticated database abstraction layer to simplify the usage for third party developers. New versions of the Joomla Platform API provide additional functionality which extends the database layer further, and includes features such as connectors to a greater variety of database servers and the query chaining to improve readability of connection code and simplify SQL coding.

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.

The Query

Joomla's database querying has changed since the new Joomla Framework was introduced "query chaining" is now the recommended method for building database queries (although string queries are still supported).

Query chaining refers to a method of connecting a number of methods, one after the other, with each method returning an object that can support the next method, improving readability and simplifying code.

To obtain a new instance of the JDatabaseQuery class we use the JDatabaseDriver getQuery method:

$db = JFactory::getDbo();
 
$query = $db->getQuery(true);

The JDatabaseDriver::getQuery takes an optional argument, $new, which can be true or false (the default being false).

To query our data source we can call a number of JDatabaseQuery methods; these methods encapsulate the data source's query language (in most cases SQL), hiding query-specific syntax from the developer and increasing the portability of the developer's source code.

Some of the more frequently used methods include; select, from, join, where and order. There are also methods such as insert, update and delete for modifying records in the data store. By chaining these and other method calls, you can create almost any query against your data store without compromising portability of your code.

Selecting Records from a Single Table

Below is an example of creating a database query using the JDatabaseQuery class. Using the select, from, where and order methods, we can create queries which are flexible, easily readable and portable:

// Get a db connection.
$db = JFactory::getDbo();
 
// Create a new query object.
$query = $db->getQuery(true);
 
// Select all records from the user profile table where key begins with "custom.".
// Order it by the ordering field.
$query->select($db->quoteName(array('user_id', 'profile_key', 'profile_value', 'ordering')));
$query->from($db->quoteName('#__user_profiles'));
$query->where($db->quoteName('profile_key') . ' LIKE '. $db->quote('\'custom.%\''));
$query->order('ordering ASC');
 
// Reset the query using our newly populated query object.
$db->setQuery($query);
 
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();

The query can also be chained to simplify further:

$query
    ->select($db->quoteName(array('user_id', 'profile_key', 'profile_value', 'ordering')))
    ->from($db->quoteName('#__user_profiles'))
    ->where($db->quoteName('profile_key') . ' LIKE '. $db->quote('\'custom.%\''))
    ->order('ordering ASC');

Chaining can become useful when queries become longer and more complex.

Grouping can be achieved simply too. The following query would count the number of articles in each category

$query
    ->select( array('catid', 'COUNT(*)') )
    ->from($db->quoteName('#__content'))
    ->group($db->quoteName('catid'));

Selecting Records from Multiple Tables

Using the JDatabaseQuery's join methods, we can select records from multiple related tables. The generic "join" method takes two arguments; the join "type" (inner, outer, left, right) and the join condition. In the following example you will notice that we can use all of the keywords we would normally use if we were writing a native SQL query, including the AS keyword for aliasing tables and the ON keyword for creating relationships between tables. Also note that the table alias is used in all methods which reference table columns (I.e. select, where, order).

// Get a db connection.
$db = JFactory::getDbo();
 
// Create a new query object.
$query = $db->getQuery(true);
 
// Select all articles for users who have a username which starts with 'a'.
// Order it by the created date.
// Note by putting 'a' as a second parameter will generate `#__content` AS `a`
$query
    ->select($db->quoteName(array('a.*', 'b.username', 'b.name')))
    ->from($db->quoteName('#__content', 'a'))
    ->join('INNER', $db->quoteName('#__users', 'b') . ' ON (' . $db->quoteName('a.created_by') . ' = ' . $db->quoteName('b.id') . ')')
    ->where($db->quoteName('b.username') . ' LIKE \'a%\'')
    ->order($db->quoteName('a.created') . ' DESC');
 
// Reset the query using our newly populated query object.
$db->setQuery($query);
 
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();

The join method above enables us to query both the content and user tables, retrieving articles with their author details. There are also convenience methods for joins:

We can use multiple joins to query across more than two tables:

$query
    ->select($db->quoteName(array('a.*', 'b.username', 'b.name', 'c.*', 'd.*')))
    ->from($db->quoteName('#__content', 'a'))
    ->join('INNER', $db->quoteName('#__users', 'b') . ' ON (' . $db->quoteName('a.created_by') . ' = ' . $db->quoteName('b.id') . ')')
    ->join('LEFT', $db->quoteName('#__user_profiles', 'c') . ' ON (' . $db->quoteName('b.id') . ' = ' . $db->quoteName('c.user_id') . ')')
    ->join('RIGHT', $db->quoteName('#__categories', 'd') . ' ON (' . $db->quoteName('a.catid') . ' = ' . $db->quoteName('d.id') . ')')
    ->where($db->quoteName('b.username') . ' LIKE \'a%\'')
    ->order($db->quoteName('a.created') . ' DESC');

Notice how chaining makes the source code much more readable for these longer queries.

In some cases, you will also need to use the AS clause when selecting items to avoid column name conflicts. In this case, multiple select statements can be chained in conjunction with using the second parameter of $db->quoteName.

$query
    ->select($db->quoteName('a.*'))
    ->select($db->quoteName('b.username', 'username'))
    ->select($db->quoteName('b.name', 'name'))
    ->from($db->quoteName('#__content', 'a'))
    ->join('INNER', $db->quoteName('#__users', 'b') . ' ON (' . $db->quoteName('a.created_by') . ' = ' . $db->quoteName('b.id') . ')')
    ->where($db->quoteName('b.username') . ' LIKE \'a%\'')
    ->order($db->quoteName('a.created') . ' DESC');

A second array can also be used as the second parameter of the select statement to populate the values of the AS clause. Remember to include nulls in the second array to correspond to columns in the first array that you don't want to use the AS clause for:

$query
    ->select($db->quoteName(array('a.*', 'b.username', 'b.name'), array('', 'username', 'name'))
    ->from($db->quoteName('#__content', 'a'))
    ->join('INNER', $db->quoteName('#__users', 'b') . ' ON (' . $db->quoteName('a.created_by') . ' = ' . $db->quoteName('b.id') . ')')
    ->where($db->quoteName('b.username') . ' LIKE \'a%\'')
    ->order($db->quoteName('a.created') . ' DESC');

Query Results

The database class contains many methods for working with a query's result set.

Single Value Result

loadResult()

Use loadResult() when you expect just a single value back from your database query.

id name email username
1 John Smith johnsmith@domain.example johnsmith
2 Magda Hellman magda_h@domain.example magdah
3 Yvonne de Gaulle ydg@domain.example ydegaulle

This is often the result of a 'count' query to get a number of records:

$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('COUNT(*)');
$query->from($db->quoteName('#__my_table'));
$query->where($db->quoteName('name')." = ".$db->quote($value));
 
// Reset the query using our newly populated query object.
$db->setQuery($query);
$count = $db->loadResult();

or where you are just looking for a single field from a single row of the table (or possibly a single field from the first row returned).

$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('field_name');
$query->from($db->quoteName('#__my_table'));
$query->where($db->quoteName('some_name')." = ".$db->quote($some_value));
 
$db->setQuery($query);
$result = $db->loadResult();

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.

id name email username
1 John Smith johnsmith@domain.example johnsmith
2 Magda Hellman magda_h@domain.example magdah
3 Yvonne de Gaulle ydg@domain.example ydegaulle

loadRow()

loadRow() returns an indexed array from a single record in the table:

. . .
$db->setQuery($query);
$row = $db->loadRow();
print_r($row);

will give:

Array ( [0] => 1 [1] => John Smith [2] => johnsmith@domain.example [3] => johnsmith ) 

You can access the individual values by using:

$row['index'] // e.g. $row['2']

Notes:

  1. The array indices are numeric starting from zero.
  2. Whilst you can repeat the call to get further rows, one of the functions that returns multiple rows might be more useful.

loadAssoc()

loadAssoc() returns an associated array from a single record in the table:

. . .
$db->setQuery($query);
$row = $db->loadAssoc();
print_r($row);

will give:

Array ( [id] => 1 [name] => John Smith [email] => johnsmith@domain.example [username] => johnsmith )

You can access the individual values by using:

$row['name'] // e.g. $row['name']

Notes:

  1. Whilst you can repeat the call to get further rows, one of the functions that returns multiple rows might be more useful.

loadObject()

loadObject returns a PHP object from a single record in the table:

. . .
$db->setQuery($query);
$result = $db->loadObject();
print_r($result);

will give:

stdClass Object ( [id] => 1 [name] => John Smith [email] => johnsmith@domain.example [username] => johnsmith )

You can access the individual values by using:

$result->index // e.g. $result->email

Notes:

  1. Whilst you can repeat the call to get further rows, one of the functions that returns multiple rows might be more useful.

Single Column Results

Each of these results functions will return a single column from the database.

id name email username
1 John Smith johnsmith@domain.example johnsmith
2 Magda Hellman magda_h@domain.example magdah
3 Yvonne de Gaulle ydg@domain.example ydegaulle

loadColumn()

loadColumn() returns an indexed array from a single column in the table:

$query->select('name'));
      ->from . . .";
. . .
$db->setQuery($query);
$column= $db->loadColumn();
print_r($column);

will give:

Array ( [0] => John Smith [1] => Magda Hellman [2] => Yvonne de Gaulle )

You can access the individual values by using:

$column['index'] // e.g. $column['2']

Notes:

  1. The array indices are numeric starting from zero.
  2. loadColumn() is equivalent to loadColumn(0).

loadColumn($index)

loadColumn($index) returns an indexed array from a single column in the table:

$query->select(array('name', 'email', 'username'));
      ->from . . .";
. . .
$db->setQuery($query);
$column= $db->loadColumn(1);
print_r($column);

will give:

Array ( [0] => johnsmith@domain.example [1] => magda_h@domain.example [2] => ydg@domain.example )

You can access the individual values by using:

$column['index'] // e.g. $column['2']

loadColumn($index) allows you to iterate through a series of columns in the results

. . .
$db->setQuery($query);
for ( $i = 0; $i <= 2; $i++ ) {
  $column= $db->loadColumn($i);
  print_r($column);
}

will give:

Array ( [0] => John Smith [1] => Magda Hellman [2] => Yvonne de Gaulle )
Array ( [0] => johnsmith@domain.example [1] => magda_h@domain.example [2] => ydg@domain.example )
Array ( [0] => johnsmith [1] => magdah [2] => ydegaulle )

Notes:

  1. The array indices are numeric starting from zero.

Multi-Row Results

Each of these results functions will return multiple records from the database.

id name email username
1 John Smith johnsmith@domain.example johnsmith
2 Magda Hellman magda_h@domain.example magdah
3 Yvonne de Gaulle ydg@domain.example ydegaulle

loadRowList()

loadRowList() returns an indexed array of indexed arrays from the table records returned by the query:

. . .
$db->setQuery($query);
$row = $db->loadRowList();
print_r($row);

will give (with line breaks added for clarity):

Array ( 
[0] => Array ( [0] => 1 [1] => John Smith [2] => johnsmith@domain.example [3] => johnsmith ) 
[1] => Array ( [0] => 2 [1] => Magda Hellman [2] => magda_h@domain.example [3] => magdah ) 
[2] => Array ( [0] => 3 [1] => Yvonne de Gaulle [2] => ydg@domain.example [3] => ydegaulle ) 
)

You can access the individual rows by using:

$row['index'] // e.g. $row['2']

and you can access the individual values by using:

$row['index']['index'] // e.g. $row['2']['3']

Notes:

  1. The array indices are numeric starting from zero.

loadAssocList()

loadAssocList() returns an indexed array of associated arrays from the table records returned by the query:

. . .
$db->setQuery($query);
$row = $db->loadAssocList();
print_r($row);

will give (with line breaks added for clarity):

Array ( 
[0] => Array ( [id] => 1 [name] => John Smith [email] => johnsmith@domain.example [username] => johnsmith ) 
[1] => Array ( [id] => 2 [name] => Magda Hellman [email] => magda_h@domain.example [username] => magdah ) 
[2] => Array ( [id] => 3 [name] => Yvonne de Gaulle [email] => ydg@domain.example [username] => ydegaulle ) 
) 

You can access the individual rows by using:

$row['index'] // e.g. $row['2']

and you can access the individual values by using:

$row['index']['column_name'] // e.g. $row['2']['email']

loadAssocList($key)

loadAssocList('key') returns an associated array - indexed on 'key' - of associated arrays from the table records returned by the query:

. . .
$db->setQuery($query);
$row = $db->loadAssocList('username');
print_r($row);

will give (with line breaks added for clarity):

Array ( 
[johnsmith] => Array ( [id] => 1 [name] => John Smith [email] => johnsmith@domain.example [username] => johnsmith ) 
[magdah] => Array ( [id] => 2 [name] => Magda Hellman [email] => magda_h@domain.example [username] => magdah ) 
[ydegaulle] => Array ( [id] => 3 [name] => Yvonne de Gaulle [email] => ydg@domain.example [username] => ydegaulle ) 
)

You can access the individual rows by using:

$row['key_value'] // e.g. $row['johnsmith']

and you can access the individual values by using:

$row['key_value']['column_name'] // e.g. $row['johnsmith']['email']

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.

loadObjectList()

loadObjectList() returns an indexed array of PHP objects from the table records returned by the query:

. . .
$db->setQuery($query);
$row = $db->loadObjectList();
print_r($row);

will give (with line breaks added for clarity):

Array ( 
[0] => stdClass Object ( [id] => 1 [name] => John Smith 
    [email] => johnsmith@domain.example [username] => johnsmith ) 
[1] => stdClass Object ( [id] => 2 [name] => Magda Hellman 
    [email] => magda_h@domain.example [username] => magdah ) 
[2] => stdClass Object ( [id] => 3 [name] => Yvonne de Gaulle 
    [email] => ydg@domain.example [username] => ydegaulle ) 
)

You can access the individual rows by using:

$row['index'] // e.g. $row['2']

and you can access the individual values by using:

$row['index']->name // e.g. $row['2']->email

loadObjectList('key')

loadObjectList($key) returns an associated array - indexed on 'key' - of objects from the table records returned by the query:

. . .
$db->setQuery($query);
$row = $db->loadObjectList('username');
print_r($row);

will give (with line breaks added for clarity):

Array ( 
[johnsmith] => stdClass Object ( [id] => 1 [name] => John Smith 
    [email] => johnsmith@domain.example [username] => johnsmith ) 
[magdah] => stdClass Object ( [id] => 2 [name] => Magda Hellman 
    [email] => magda_h@domain.example [username] => magdah ) 
[ydegaulle] => stdClass Object ( [id] => 3 [name] => Yvonne de Gaulle 
    [email] => ydg@domain.example [username] => ydegaulle ) 
)

You can access the individual rows by using:

$row['key_value'] // e.g. $row['johnsmith']

and you can access the individual values by using:

$row['key_value']->column_name // e.g. $row['johnsmith']->email

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.

. . .
$db->setQuery($query);
$db->execute();
$num_rows = $db->getNumRows();
print_r($num_rows);
$result = $db->loadRowList();

will return

3

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 libraries\joomla\database\database\mysql.php on line 344