Difference between revisions of "Selecting data using JDatabase"

From Joomla! Documentation

(Corrected some URLs. Other formatting changes.)
 
(56 intermediate revisions by 19 users not shown)
Line 1: Line 1:
{{version|2.5,3.x}}
+
<noinclude><languages /></noinclude>
{{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.}}
+
<noinclude>{{Joomla version|version=3.x}}{{Joomla version|version=2.5|status=eos}}</noinclude>
 +
{{-}}
 +
{{tip|<translate><!--T:1-->
 +
Note many examples online use <code>$db->query()</code> instead of <code>$db->execute()</code>. This was the old method in Joomla 1.5 and 2.5 and will throw a deprecated notice in Joomla 3.0+.</translate>|title=<translate><!--T:2-->
 +
Version Note</translate>}}
  
This tutorial is split into two independent parts:
+
<translate><!--T:3-->
* Inserting, updating and removing data from the database. It also touches on transactions.
+
This tutorial is split into two independent parts:</translate>
* Selecting data from one or more tables and retrieving it in a variety of different forms
+
<translate><!--T:4-->
 +
* Inserting, updating and removing data from the database.</translate>
 +
<translate><!--T:5-->
 +
* Selecting data from one or more tables and retrieving it in a variety of different forms</translate>
  
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]]
+
<translate><!--T:6-->
 +
This section of the documentation looks at selecting data from a database table and retrieving it in a variety of formats. Also see the [[S:MyLanguage/Inserting,_Updating_and_Removing_data_using_JDatabase|Inserting, Updating and Removing Data using JDatabase article]]</translate>
  
== Introduction==
+
<translate>
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.
+
== Introduction == <!--T:7-->
 +
</translate>
 +
<translate><!--T:8-->
 +
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.</translate>
  
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.
+
<translate><!--T:9-->
 +
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.</translate>
  
==The Query==
+
<translate>
 +
==The Query== <!--T:10-->
 +
</translate>
 +
<translate><!--T:11-->
 +
Joomla's database querying changed with the introduction of Joomla 1.6. The recommended way of building database queries is through ''query chaining'' (although string queries are still supported).</translate>
  
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).
+
<translate><!--T:12-->
 +
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.</translate>
  
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.
+
<translate><!--T:13-->
 +
To obtain a new instance of the JDatabaseQuery class we use the JDatabaseDriver getQuery method:</translate>
  
To obtain a new instance of the JDatabaseQuery class we use the JDatabaseDriver getQuery method:
+
<syntaxhighlight lang="php">
 
 
<source lang="php">
 
 
$db = JFactory::getDbo();
 
$db = JFactory::getDbo();
  
 
$query = $db->getQuery(true);
 
$query = $db->getQuery(true);
</source>
+
</syntaxhighlight>
  
The JDatabaseDriver::getQuery takes an optional argument, $new, which can be true or false (the default being false).
+
<translate><!--T:14-->
 +
The JDatabaseDriver::getQuery takes an optional argument, $new, which can be true or false (the default being false).</translate>
  
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.  
+
<translate><!--T:15-->
 +
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.</translate>
  
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.
+
<translate><!--T:16-->
 +
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</translate>.
  
==Selecting Records from a Single Table==
+
<translate>
 +
==Selecting Records from a Single Table== <!--T:17-->
 +
</translate>
  
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:
+
<translate><!--T:18-->
 +
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:</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
// Get a db connection.
 
// Get a db connection.
 
$db = JFactory::getDbo();
 
$db = JFactory::getDbo();
Line 48: Line 70:
 
$query->select($db->quoteName(array('user_id', 'profile_key', 'profile_value', 'ordering')));
 
$query->select($db->quoteName(array('user_id', 'profile_key', 'profile_value', 'ordering')));
 
$query->from($db->quoteName('#__user_profiles'));
 
$query->from($db->quoteName('#__user_profiles'));
$query->where($db->quoteName('profile_key') . ' LIKE '. $db->quote('\'custom.%\''));
+
$query->where($db->quoteName('profile_key') . ' LIKE ' . $db->quote('custom.%'));
 
$query->order('ordering ASC');
 
$query->order('ordering ASC');
  
Line 56: Line 78:
 
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
 
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
 
$results = $db->loadObjectList();
 
$results = $db->loadObjectList();
</source>
+
</syntaxhighlight>
  
The query can also be chained to simplify further:
+
(Here the ''quoteName()'' function adds appropriate quotes around the column names to avoid conflicts with any database reserved word, now or in the future.)
  
<source lang="php">
+
<translate><!--T:19-->
 +
The query can also be chained to simplify further:</translate>
 +
 
 +
<syntaxhighlight lang="php">
 
$query
 
$query
 
     ->select($db->quoteName(array('user_id', 'profile_key', 'profile_value', 'ordering')))
 
     ->select($db->quoteName(array('user_id', 'profile_key', 'profile_value', 'ordering')))
 
     ->from($db->quoteName('#__user_profiles'))
 
     ->from($db->quoteName('#__user_profiles'))
     ->where($db->quoteName('profile_key') . ' LIKE '. $db->quote('\'custom.%\''))
+
     ->where($db->quoteName('profile_key') . ' LIKE ' . $db->quote('custom.%'))
 
     ->order('ordering ASC');
 
     ->order('ordering ASC');
</source>
+
</syntaxhighlight>
 +
 
 +
<translate><!--T:20-->
 +
Chaining method calls improves code readability and reduces code bloat as queries become longer and more complex.</translate>
 +
 
 +
<translate><!--T:21-->
 +
Grouping can be achieved simply too.  The following query would count the number of articles in each category.</translate>
 +
 
 +
<syntaxhighlight lang="php">
 +
$query
 +
    ->select(array('catid', 'COUNT(*)'))
 +
    ->from($db->quoteName('#__content'))
 +
    ->group($db->quoteName('catid'));
 +
</syntaxhighlight>
 +
 
 +
<translate><!--T:22-->
 +
A limit can be set to a query using ''setLimit''. For example in the following query, it would return up to 10 records.</translate>
  
Chaining can become useful when queries become longer and more complex.
+
<syntaxhighlight lang="php">
 +
$query
 +
    ->select($db->quoteName(array('user_id', 'profile_key', 'profile_value', 'ordering')))
 +
    ->from($db->quoteName('#__user_profiles'))
 +
    ->setLimit('10');
 +
</syntaxhighlight>
  
==Selecting Records from Multiple Tables==
+
<translate>
  
Using the JDatabaseQuery's [http://api.joomla.org/Joomla-Platform/Database/JDatabaseQuery.html#join 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).
+
==Selecting Records from Multiple Tables== <!--T:23-->
 +
</translate>
 +
<translate><!--T:24-->
 +
Using the JDatabaseQuery's [https://api.joomla.org/cms-3/classes/JDatabaseQuery.html#method_join 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).</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
// Get a db connection.
 
// Get a db connection.
 
$db = JFactory::getDbo();
 
$db = JFactory::getDbo();
Line 83: Line 132:
 
// 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($db->quoteName(array('a.*', 'b.username', 'b.name')));
+
     ->select(array('a.*', 'b.username', 'b.name'))
    // Note by putting 'a' as a second parameter will generate `#__content` AS `a`
+
     ->from($db->quoteName('#__content', 'a'))
     ->from($db->quoteName('#__content', 'a')
+
     ->join('INNER', $db->quoteName('#__users', 'b') . ' ON ' . $db->quoteName('a.created_by') . ' = ' . $db->quoteName('b.id'))
     ->join('INNER', $db->quoteName('#__users', 'b') . ' ON (' . $db->quoteName('a.created_by') . ' = ' . $db-quoteName('b.id') . ')')
+
     ->where($db->quoteName('b.username') . ' LIKE ' . $db->quote('a%'))
     ->where($db->quoteName('b.username') . ' LIKE \'a%\'')
 
 
     ->order($db->quoteName('a.created') . ' DESC');
 
     ->order($db->quoteName('a.created') . ' DESC');
  
Line 96: Line 145:
 
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
 
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
 
$results = $db->loadObjectList();
 
$results = $db->loadObjectList();
</source>
+
</syntaxhighlight>
 +
 
 +
<translate><!--T:25-->
 +
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:</translate>
 +
* [https://api.joomla.org/cms-3/classes/JDatabaseQuery.html#method_innerJoin innerJoin()]
 +
* [https://api.joomla.org/cms-3/classes/JDatabaseQuery.html#method_leftJoin leftJoin()]
 +
* [https://api.joomla.org/cms-3/classes/JDatabaseQuery.html#method_rightJoin rightJoin()]
 +
* [https://api.joomla.org/cms-3/classes/JDatabaseQuery.html#method_outerJoin outerJoin()]
 +
 
 +
<translate><!--T:26-->
 +
We can use multiple joins to query across more than two tables:</translate>
 +
 
 +
<syntaxhighlight lang="php">
 +
$query
 +
    ->select(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 ' . $db->quote('a%'))
 +
    ->order($db->quoteName('a.created') . ' DESC');
 +
</syntaxhighlight>
 +
 
 +
<translate><!--T:27-->
 +
Notice how chaining makes the source code much more readable for these longer queries.</translate>
  
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.
+
<translate><!--T:28-->
 +
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.</translate>
 +
 
 +
<syntaxhighlight lang="php">
 +
$query
 +
    ->select('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 ' . $db->quote('a%'))
 +
    ->order($db->quoteName('a.created') . ' DESC');
 +
</syntaxhighlight>
  
We can use multiple joins to query across more than two tables:
+
<translate><!--T:29-->
 +
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:</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
$query
 
$query
     ->select($db->quoteName(array('a.*', 'b.username', 'b.name', 'c.*', 'd.*')))
+
    ->select(array('a.*'))
     ->from($db->quoteName('#__content', a))
+
     ->select($db->quoteName(array('b.username', 'b.name'), array('username', 'name')))
     ->join('INNER', $db->quoteName('#__users', 'b') . ' ON (' . $db->quoteName('a.created_by') . ' = ' . $db-quoteName('b.id') . ')')
+
     ->from($db->quoteName('#__content', 'a'))
     ->join('LEFT', $db->quoteName('#__user_profiles', 'c') . ' ON (' . $db->quoteName('b.id') . ' = ' . $db-quoteName('c.user_id') . ')')
+
     ->join('INNER', $db->quoteName('#__users', 'b') . ' ON ' . $db->quoteName('a.created_by') . ' = ' . $db->quoteName('b.id'))
    ->join('RIGHT', $db->quoteName('#__categories', 'd') . ' ON (' . $db->quoteName('a.catid') . ' = ' . $db-quoteName('d.id') . ')')
+
     ->where($db->quoteName('b.username') . ' LIKE ' . $db->quote('a%'))
    ->where($db->quoteName('b.username') . ' LIKE \'a%\'')
 
 
     ->order($db->quoteName('a.created') . ' DESC');
 
     ->order($db->quoteName('a.created') . ' DESC');
</source>
+
</syntaxhighlight>
  
Notice how chaining makes the source code much more readable for these longer queries.
+
<translate>
 +
==Using OR in queries== <!--T:140--> </translate>
 +
<translate>
 +
<!--T:141-->
 +
When using multiple WHERE clauses in your query, they will be treated as an AND.
  
==Query Results ==
+
<!--T:142-->
 +
So, for example, the query below will return results where the 'name' field AND the 'state' field match.</translate>
 +
<syntaxhighlight lang="php">
 +
$query = $db
 +
    ->getQuery(true)
 +
    ->select('COUNT(*)')
 +
    ->from($db->quoteName('#__my_table'))
 +
    ->where($db->quoteName('name') . " = " . $db->quote($value)
 +
    ->where($db->quoteName('state') . " = " . $db->quote($state));
 +
</syntaxhighlight>
 +
<translate>
 +
<!--T:143-->
 +
To use a WHERE clause as an OR, the query can be written like this</translate>
 +
<syntaxhighlight lang="php">
 +
$query = $db
 +
    ->getQuery(true)
 +
    ->select('COUNT(*)')
 +
    ->from($db->quoteName('#__my_table'))
 +
    ->where($db->quoteName('name') . " = " . $db->quote($name_one), 'OR')
 +
    ->where($db->quoteName('name') . " = " . $db->quote($name_two));
 +
</syntaxhighlight>
 +
<translate>
 +
<!--T:144-->
 +
it can also be written like this</translate>
 +
<syntaxhighlight lang="php">
 +
$query = $db
 +
    ->getQuery(true)
 +
    ->select('COUNT(*)')
 +
    ->from($db->quoteName('#__my_table'))
 +
    ->where($db->quoteName('name') . " = " . $db->quote($name_one)
 +
    ->orWhere($db->quoteName('name') . " = " . $db->quote($name_two));
 +
</syntaxhighlight>
 +
 
 +
<translate>
 +
==Query Results == <!--T:30-->
 +
</translate>
 +
<translate><!--T:31-->
 
The database class contains many methods for working with a query's result set.
 
The database class contains many methods for working with a query's result set.
  
=== Single Value Result ===
+
<!--T:145-->
==== loadResult() ====
+
If there are no matches to the query, the result will be null.
Use '''loadResult()''' when you expect just a single value back from your database query.  
+
</translate>
 +
 
 +
<translate>
 +
=== Single Value Result === <!--T:32-->
 +
</translate>
 +
<translate>
 +
==== loadResult() ==== <!--T:33-->
 +
</translate>
 +
<translate><!--T:34-->
 +
Use '''loadResult()''' when you expect just a single value back from your database query.</translate>
  
 
{| class="wikitable" style="text-align:center"
 
{| class="wikitable" style="text-align:center"
 
|-
 
|-
! id !! name !! email !! username
+
! <translate><!--T:35-->
|-  
+
id</translate> !! <translate><!--T:36-->
| 1 || style="background:yellow" | John Smith || johnsmith@domain.example || johnsmith
+
name</translate> !! <translate><!--T:37-->
 +
email</translate> !! <translate><!--T:38-->
 +
username</translate>
 +
|-
 +
| 1 || style="background:yellow" | John Smith || <translate><!--T:39-->
 +
johnsmith@domain.example</translate> || johnsmith
 
|-
 
|-
| 2 || Magda Hellman || magda_h@domain.example || magdah
+
| 2 || Magda Hellman || <translate><!--T:40-->
 +
magda_h@domain.example</translate> || magdah
 
|-
 
|-
| 3 || Yvonne de Gaulle || ydg@domain.example || ydegaulle
+
| 3 || Yvonne de Gaulle || <translate><!--T:41-->
 +
ydg@domain.example</translate> || ydegaulle
 
|}
 
|}
  
This is often the result of a 'count' query to get a number of records:
+
<translate><!--T:42-->
<source lang="php">
+
This is often the result of a 'count' query to get a number of records:</translate>
 +
 
 +
<syntaxhighlight lang="php">
 
$db = JFactory::getDbo();
 
$db = JFactory::getDbo();
$query = $db->getQuery(true);
+
$query = $db
$query->select('COUNT(*)');
+
    ->getQuery(true)
$query->from($db->quoteName'#__my_table');
+
    ->select('COUNT(*)')
$query->where($db->quoteName('name')." = ".$db->quote($value));
+
    ->from($db->quoteName('#__my_table'))
 +
    ->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.
 
$db->setQuery($query);
 
$db->setQuery($query);
 
$count = $db->loadResult();
 
$count = $db->loadResult();
</source>
+
</syntaxhighlight>
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).
+
<translate><!--T:134-->
<source lang='php'>
+
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).</translate>
 +
<syntaxhighlight lang='php'>
 
$db = JFactory::getDbo();
 
$db = JFactory::getDbo();
$query = $db->getQuery(true);
+
$query = $db
$query->select('field_name');
+
    ->getQuery(true)
$query->from($db->quoteName('#__my_table'));
+
    ->select('field_name')
$query->where($db->quoteName('some_name')." = ".$db->quote($some_value));
+
    ->from($db->quoteName('#__my_table'))
 +
    ->where($db->quoteName('some_name') . " = " . $db->quote($some_value));
  
 
$db->setQuery($query);
 
$db->setQuery($query);
 
$result = $db->loadResult();
 
$result = $db->loadResult();
</source>
+
</syntaxhighlight>
 +
 
 +
<translate>
 +
===Single Row Results === <!--T:43-->
 +
</translate>
 +
<translate><!--T:44-->
 +
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.</translate>
  
===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.
 
 
{| class="wikitable" style="text-align:center"
 
{| class="wikitable" style="text-align:center"
 
|-
 
|-
! id !! name !! email !! username
+
! <translate><!--T:45-->
 +
id</translate> !! <translate><!--T:46-->
 +
name</translate> !! <translate><!--T:47-->
 +
email</translate> !! <translate><!--T:48-->
 +
username</translate>
 
|- style="background:yellow"
 
|- style="background:yellow"
| 1 || John Smith || johnsmith@domain.example || johnsmith
+
| 1 || John Smith || <translate><!--T:49-->
 +
johnsmith@domain.example</translate> || johnsmith
 
|-
 
|-
| 2 || Magda Hellman || magda_h@domain.example || magdah
+
| 2 || Magda Hellman || <translate><!--T:50-->
 +
magda_h@domain.example</translate> || magdah
 
|-
 
|-
| 3 || Yvonne de Gaulle || ydg@domain.example || ydegaulle
+
| 3 || Yvonne de Gaulle || <translate><!--T:51-->
 +
ydg@domain.example</translate> || ydegaulle
 
|}
 
|}
  
==== loadRow() ====
+
<translate>
loadRow() returns an indexed array from a single record in the table:  
+
==== loadRow() ==== <!--T:52-->
<source lang='php'>
+
</translate>
 +
<translate><!--T:53-->
 +
''loadRow()'' returns an indexed array from a single record in the table:</translate>
 +
 
 +
<syntaxhighlight lang='php'>
 
. . .
 
. . .
 
$db->setQuery($query);
 
$db->setQuery($query);
 
$row = $db->loadRow();
 
$row = $db->loadRow();
 
print_r($row);
 
print_r($row);
</source>
+
</syntaxhighlight>
will give:
+
<translate><!--T:133-->
<pre>Array ( [0] => 1 [1] => John Smith [2] => johnsmith@domain.example [3] => johnsmith ) </pre>
+
will give:</translate>
 +
<pre>Array ( [0] => 1, [1] => John Smith, [2] => johnsmith@domain.example, [3] => johnsmith ) </pre>
 +
 
 +
<translate><!--T:54-->
 +
You can access the individual values by using:</translate><pre>$row['index'] // e.g. $row['2']</pre>
  
You can access the individual values by using:<pre>$row['index'] // e.g. $row['2']</pre>
+
<translate><!--T:55-->
 +
Notes:</translate>
 +
<translate><!--T:56-->
 +
# The array indices are numeric starting from zero.</translate>
 +
<translate><!--T:57-->
 +
# Whilst you can repeat the call to get further rows, one of the functions that returns multiple rows might be more useful.</translate>
  
Notes:
+
<translate>
# The array indices are numeric starting from zero.
+
==== loadAssoc() ==== <!--T:58-->
# Whilst you can repeat the call to get further rows, one of the functions that returns multiple rows might be more useful.
+
</translate>
 +
<translate><!--T:59-->
 +
''loadAssoc()'' returns an associated array from a single record in the table:</translate>
  
==== loadAssoc() ====
+
<syntaxhighlight lang='php'>
loadAssoc() returns an associated array from a single record in the table:
 
<source lang='php'>
 
 
. . .
 
. . .
 
$db->setQuery($query);
 
$db->setQuery($query);
 
$row = $db->loadAssoc();
 
$row = $db->loadAssoc();
 
print_r($row);
 
print_r($row);
</source>
+
</syntaxhighlight>
 +
 
 +
<translate><!--T:60-->
 
will give:
 
will give:
<pre>Array ( [id] => 1 [name] => John Smith [email] => johnsmith@domain.example [username] => johnsmith )</pre>
+
<pre>Array ( [id] => 1, [name] => John Smith, [email] => johnsmith@domain.example, [username] => johnsmith )</pre></translate>
  
You can access the individual values by using:<pre>$row['name'] // e.g. $row['name']</pre>
+
<translate><!--T:61-->
 +
You can access the individual values by using:</translate><pre>$row['name'] // e.g. $row['email']</pre>
  
 +
<translate><!--T:62-->
 
Notes:
 
Notes:
# Whilst you can repeat the call to get further rows, one of the functions that returns multiple rows might be more useful.
+
# Whilst you can repeat the call to get further rows, one of the functions that returns multiple rows might be more useful.</translate>
  
==== loadObject() ====
+
<translate>
loadObject returns a PHP object from a single record in the table:  
+
==== loadObject() ==== <!--T:63-->
<source lang='php'>
+
</translate>
 +
<translate><!--T:64-->
 +
loadObject returns a PHP object from a single record in the table:</translate>
 +
 
 +
<syntaxhighlight lang='php'>
 
. . .
 
. . .
 
$db->setQuery($query);
 
$db->setQuery($query);
 
$result = $db->loadObject();
 
$result = $db->loadObject();
 
print_r($result);
 
print_r($result);
</source>
+
</syntaxhighlight>
 +
 
 +
<translate><!--T:65-->
 
will give:
 
will give:
<pre>stdClass Object ( [id] => 1 [name] => John Smith [email] => johnsmith@domain.example [username] => johnsmith )</pre>
+
<pre>stdClass Object ( [id] => 1, [name] => John Smith, [email] => johnsmith@domain.example, [username] => johnsmith )</pre></translate>
  
You can access the individual values by using:<pre>$result->index // e.g. $result->email</pre>
+
<translate><!--T:66-->
 +
You can access the individual values by using:</translate><pre>$result->index // e.g. $result->email</pre>
  
 +
<translate><!--T:67-->
 
Notes:
 
Notes:
# Whilst you can repeat the call to get further rows, one of the functions that returns multiple rows might be more useful.
+
# Whilst you can repeat the call to get further rows, one of the functions that returns multiple rows might be more useful.</translate>
  
===Single Column Results ===
+
<translate>
Each of these results functions will return a single column from the database.  
+
===Single Column Results === <!--T:68-->
 +
</translate>
 +
<translate><!--T:69-->
 +
Each of these results functions will return a single column from the database.</translate>
  
 
{| class="wikitable" style="text-align:center"
 
{| class="wikitable" style="text-align:center"
 
|-
 
|-
! id !! name !! email !! username
+
! <translate><!--T:70-->
|-  
+
id</translate> !! <translate><!--T:71-->
| 1 || style="background:yellow" | John Smith || johnsmith@domain.example || johnsmith
+
name</translate> !! <translate><!--T:72-->
 +
email</translate> !! <translate><!--T:73-->
 +
username</translate>
 +
|-
 +
| 1 || style="background:yellow" | John Smith || <translate><!--T:74-->
 +
johnsmith@domain.example</translate> || johnsmith
 
|-
 
|-
| 2 || style="background:yellow" | Magda Hellman || magda_h@domain.example || magdah
+
| 2 || style="background:yellow" | Magda Hellman || <translate><!--T:75-->
 +
magda_h@domain.example</translate> || magdah
 
|-
 
|-
| 3 || style="background:yellow" | Yvonne de Gaulle || ydg@domain.example || ydegaulle
+
| 3 || style="background:yellow" | Yvonne de Gaulle || <translate><!--T:76-->
 +
ydg@domain.example</translate> || ydegaulle
 
|}
 
|}
  
==== loadColumn() ====
+
<translate>
loadColumn() returns an indexed array from a single column in the table:  
+
==== loadColumn() ==== <!--T:77-->
<source lang='php'>
+
</translate>
 +
<translate><!--T:78-->
 +
''loadColumn()'' returns an indexed array from a single column in the table:</translate>
 +
 
 +
<syntaxhighlight lang='php'>
 
$query->select('name'));
 
$query->select('name'));
 
       ->from . . .";
 
       ->from . . .";
Line 242: Line 438:
 
$column= $db->loadColumn();
 
$column= $db->loadColumn();
 
print_r($column);
 
print_r($column);
</source>
+
</syntaxhighlight>
will give:
+
 
<pre>Array ( [0] => John Smith [1] => Magda Hellman [2] => Yvonne de Gaulle )</pre>
+
<translate><!--T:79-->
 +
will give:</translate>
 +
<pre>Array ( [0] => John Smith, [1] => Magda Hellman, [2] => Yvonne de Gaulle )</pre>
  
You can access the individual values by using:<pre>$column['index'] // e.g. $column['2']</pre>
+
<translate><!--T:80-->
 +
You can access the individual values by using:</translate><pre>$column['index'] // e.g. $column['2']</pre>
  
 +
<translate><!--T:81-->
 
Notes:
 
Notes:
 
# The array indices are numeric starting from zero.
 
# The array indices are numeric starting from zero.
# loadColumn() is equivalent to loadColumn(0).
+
# ''loadColumn()'' is equivalent to loadColumn(0).</translate>
  
==== loadColumn($index) ====
+
<translate>
loadColumn($index) returns an indexed array from a single column in the table:  
+
==== loadColumn($index) ==== <!--T:82-->
<source lang='php'>
+
</translate>
 +
<translate><!--T:83-->
 +
loadColumn($index) returns an indexed array from a single column in the table:</translate>
 +
 
 +
<syntaxhighlight lang='php'>
 
$query->select(array('name', 'email', 'username'));
 
$query->select(array('name', 'email', 'username'));
 
       ->from . . .";
 
       ->from . . .";
Line 261: Line 465:
 
$column= $db->loadColumn(1);
 
$column= $db->loadColumn(1);
 
print_r($column);
 
print_r($column);
</source>
+
</syntaxhighlight>
 +
 
 +
<translate><!--T:84-->
 
will give:
 
will give:
<pre>Array ( [0] => johnsmith@domain.example [1] => magda_h@domain.example [2] => ydg@domain.example )</pre>
+
<pre>Array ( [0] => johnsmith@domain.example, [1] => magda_h@domain.example, [2] => ydg@domain.example )</pre></translate>
 +
 
 +
<translate><!--T:85-->
 +
You can access the individual values by using:</translate><pre>$column['index'] // e.g. $column['2']</pre>
  
You can access the individual values by using:<pre>$column['index'] // e.g. $column['2']</pre>
+
<translate><!--T:86-->
 +
loadColumn($index) allows you to iterate through a series of columns in the results</translate>
  
loadColumn($index) allows you to iterate through a series of columns in the results
+
<syntaxhighlight lang='php'>
<source lang='php'>
 
 
. . .
 
. . .
 
$db->setQuery($query);
 
$db->setQuery($query);
Line 275: Line 484:
 
   print_r($column);
 
   print_r($column);
 
}
 
}
</source>
+
</syntaxhighlight>
will give:
+
 
<pre>Array ( [0] => John Smith [1] => Magda Hellman [2] => Yvonne de Gaulle )
+
<translate><!--T:87-->
Array ( [0] => johnsmith@domain.example [1] => magda_h@domain.example [2] => ydg@domain.example )
+
will give:</translate>
Array ( [0] => johnsmith [1] => magdah [2] => ydegaulle )</pre>
+
<pre>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 )</pre>
 
</pre>
 
</pre>
  
 +
<translate><!--T:88-->
 
Notes:
 
Notes:
# The array indices are numeric starting from zero.
+
# The array indices are numeric starting from zero.</translate>
  
=== Multi-Row Results ===
+
<translate>
Each of these results functions will return multiple records from the database.  
+
=== Multi-Row Results === <!--T:89-->
 +
</translate>
 +
<translate><!--T:90-->
 +
Each of these results functions will return multiple records from the database.</translate>
  
 
{| class="wikitable" style="text-align:center"
 
{| class="wikitable" style="text-align:center"
 
|-
 
|-
! id !! name !! email !! username
+
! <translate><!--T:91-->
 +
id</translate> !! <translate><!--T:92-->
 +
name</translate> !! <translate><!--T:93-->
 +
email</translate> !! <translate><!--T:94-->
 +
username</translate>
 
|- style="background:yellow"
 
|- style="background:yellow"
 
| 1 || John Smith || johnsmith@domain.example || johnsmith
 
| 1 || John Smith || johnsmith@domain.example || johnsmith
Line 299: Line 518:
 
|}
 
|}
  
==== loadRowList() ====
+
<translate>
loadRowList() returns an indexed array of indexed arrays from the table records returned by the query:  
+
==== loadRowList() ==== <!--T:95-->
<source lang='php'>
+
</translate>
 +
<translate><!--T:96-->
 +
''loadRowList()'' returns an indexed array of indexed arrays from the table records returned by the query:</translate>
 +
 
 +
<syntaxhighlight lang='php'>
 
. . .
 
. . .
 
$db->setQuery($query);
 
$db->setQuery($query);
 
$row = $db->loadRowList();
 
$row = $db->loadRowList();
 
print_r($row);
 
print_r($row);
</source>
+
</syntaxhighlight>
will give (with line breaks added for clarity):
+
 
<pre>Array (  
+
<translate><!--T:97-->
[0] => Array ( [0] => 1 [1] => John Smith [2] => johnsmith@domain.example [3] => johnsmith )  
+
will give (with line breaks added for clarity):</translate>
[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 )  
+
<pre>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 )
 
)</pre>
 
)</pre>
  
You can access the individual rows by using:<pre>$row['index'] // e.g. $row['2']</pre>
+
<translate><!--T:98-->
and you can access the individual values by using:<pre>$row['index']['index'] // e.g. $row['2']['3']</pre>
+
You can access the individual rows by using:</translate><pre>$row['index'] // e.g. $row['2']</pre>
 +
<translate><!--T:99-->
 +
and you can access the individual values by using:</translate><pre>$row['index']['index'] // e.g. $row['2']['3']</pre>
  
 +
<translate><!--T:100-->
 
Notes:
 
Notes:
# The array indices are numeric starting from zero.
+
# The array indices are numeric starting from zero.</translate>
 +
 
 +
<translate>==== loadAssocList() ==== <!--T:101--></translate>
 +
<translate><!--T:102-->
 +
''loadAssocList()'' returns an indexed array of associated arrays from the table records returned by the query:</translate>
  
==== loadAssocList() ====
+
<syntaxhighlight lang='php'>
loadAssocList() returns an indexed array of associated arrays from the table records returned by the query:
 
<source lang='php'>
 
 
. . .
 
. . .
 
$db->setQuery($query);
 
$db->setQuery($query);
 
$row = $db->loadAssocList();
 
$row = $db->loadAssocList();
 
print_r($row);
 
print_r($row);
</source>
+
</syntaxhighlight>
will give (with line breaks added for clarity):
+
 
<pre>Array (  
+
<translate><!--T:103-->
[0] => Array ( [id] => 1 [name] => John Smith [email] => johnsmith@domain.example [username] => johnsmith )  
+
will give (with line breaks added for clarity):</translate>
[1] => Array ( [id] => 2 [name] => Magda Hellman [email] => magda_h@domain.example [username] => magdah )  
+
<pre>Array (
[2] => Array ( [id] => 3 [name] => Yvonne de Gaulle [email] => ydg@domain.example [username] => ydegaulle )  
+
[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 )
 
) </pre>
 
) </pre>
  
You can access the individual rows by using:<pre>$row['index'] // e.g. $row['2']</pre>
+
<translate><!--T:104-->
and you can access the individual values by using:<pre>$row['index']['column_name'] // e.g. $row['2']['email']</pre>
+
You can access the individual rows by using:</translate><pre>$row['index'] // e.g. $row['2']</pre>
 +
<translate><!--T:105-->
 +
and you can access the individual values by using:</translate><pre>$row['index']['column_name'] // e.g. $row['2']['email']</pre>
  
==== loadAssocList($key) ====
+
<translate>==== loadAssocList($key) ==== <!--T:106--></translate>
loadAssocList('key') returns an associated array - indexed on 'key' - of associated arrays from the table records returned by the query:  
+
<translate><!--T:107-->
<source lang='php'>
+
''loadAssocList('key')'' returns an associated array - indexed on 'key' - of associated arrays from the table records returned by the query:</translate>
 +
 
 +
<syntaxhighlight lang='php'>
 
. . .
 
. . .
 
$db->setQuery($query);
 
$db->setQuery($query);
 
$row = $db->loadAssocList('username');
 
$row = $db->loadAssocList('username');
 
print_r($row);
 
print_r($row);
</source>
+
</syntaxhighlight>
will give (with line breaks added for clarity):
+
 
<pre>Array (  
+
<translate><!--T:108-->
[johnsmith] => Array ( [id] => 1 [name] => John Smith [email] => johnsmith@domain.example [username] => johnsmith )  
+
will give (with line breaks added for clarity):</translate>
[magdah] => Array ( [id] => 2 [name] => Magda Hellman [email] => magda_h@domain.example [username] => magdah )  
+
<pre>Array (
[ydegaulle] => Array ( [id] => 3 [name] => Yvonne de Gaulle [email] => ydg@domain.example [username] => ydegaulle )  
+
[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 )
 +
)</pre>
 +
 
 +
<translate><!--T:109-->
 +
You can access the individual rows by using:</translate><pre>$row['key_value'] // e.g. $row['johnsmith']</pre>
 +
<translate><!--T:110-->
 +
and you can access the individual values by using:</translate><pre>$row['key_value']['column_name'] // e.g. $row['johnsmith']['email']</pre>
 +
 
 +
<translate><!--T:111-->
 +
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.</translate>
 +
 
 +
<translate>==== loadAssocList($key, $column) ==== <!--T:112--></translate>
 +
<translate><!--T:113-->
 +
''loadAssocList('key', 'column')'' returns an associative array, indexed on 'key', of values from the column named 'column' returned by the query:</translate>
 +
 
 +
<syntaxhighlight lang='php'>
 +
. . .
 +
$db->setQuery($query);
 +
$row = $db->loadAssocList('id', 'username');
 +
print_r($row);
 +
</syntaxhighlight>
 +
 
 +
<translate><!--T:114-->
 +
will give (with line breaks added for clarity):</translate>
 +
<pre>Array (
 +
[1] => John Smith,
 +
[2] => Magda Hellman,
 +
[3] => Yvonne de Gaulle,
 
)</pre>
 
)</pre>
  
You can access the individual rows by using:<pre>$row['key_value'] // e.g. $row['johnsmith']</pre>
+
<translate><!--T:115-->
and you can access the individual values by using:<pre>$row['key_value']['column_name'] // e.g. $row['johnsmith']['email']</pre>
+
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.</translate>
  
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.
+
<translate>==== loadObjectList() ==== <!--T:116--></translate>
 +
<translate><!--T:117-->
 +
''loadObjectList()'' returns an indexed array of PHP objects from the table records returned by the query:</translate>
  
==== loadObjectList() ====
+
<syntaxhighlight lang='php'>
loadObjectList() returns an indexed array of PHP objects from the table records returned by the query:
 
<source lang='php'>
 
 
. . .
 
. . .
 
$db->setQuery($query);
 
$db->setQuery($query);
 
$row = $db->loadObjectList();
 
$row = $db->loadObjectList();
 
print_r($row);
 
print_r($row);
</source>
+
</syntaxhighlight>
will give (with line breaks added for clarity):
+
 
<pre>Array (  
+
<translate><!--T:118-->
[0] => stdClass Object ( [id] => 1 [name] => John Smith  
+
will give (with line breaks added for clarity):</translate>
     [email] => johnsmith@domain.example [username] => johnsmith )  
+
<pre>Array (
[1] => stdClass Object ( [id] => 2 [name] => Magda Hellman  
+
[0] => stdClass Object ( [id] => 1, [name] => John Smith,
     [email] => magda_h@domain.example [username] => magdah )  
+
     [email] => johnsmith@domain.example, [username] => johnsmith ),
[2] => stdClass Object ( [id] => 3 [name] => Yvonne de Gaulle  
+
[1] => stdClass Object ( [id] => 2, [name] => Magda Hellman,
     [email] => ydg@domain.example [username] => ydegaulle )  
+
     [email] => magda_h@domain.example, [username] => magdah ),
 +
[2] => stdClass Object ( [id] => 3, [name] => Yvonne de Gaulle,
 +
     [email] => ydg@domain.example, [username] => ydegaulle )
 
)</pre>
 
)</pre>
  
You can access the individual rows by using:<pre>$row['index'] // e.g. $row['2']</pre>
+
<translate><!--T:119-->
and you can access the individual values by using:<pre>$row['index']->name // e.g. $row['2']->email</pre>
+
You can access the individual rows by using:</translate><pre>$row['index'] // e.g. $row['2']</pre>
 +
<translate><!--T:120-->
 +
and you can access the individual values by using:</translate><pre>$row['index']->name // e.g. $row['2']->email</pre>
  
==== loadObjectList('key') ====
+
<translate>==== loadObjectList($key) ==== <!--T:121--></translate>
loadObjectList($key) returns an associated array - indexed on 'key' - of objects from the table records returned by the query:  
+
<translate><!--T:122-->
<source lang='php'>
+
''loadObjectList('key')'' returns an associated array - indexed on 'key' - of objects from the table records returned by the query:</translate>
 +
 
 +
<syntaxhighlight lang='php'>
 
. . .
 
. . .
 
$db->setQuery($query);
 
$db->setQuery($query);
 
$row = $db->loadObjectList('username');
 
$row = $db->loadObjectList('username');
 
print_r($row);
 
print_r($row);
</source>
+
</syntaxhighlight>
will give (with line breaks added for clarity):
+
 
<pre>Array (  
+
<translate><!--T:123-->
[johnsmith] => stdClass Object ( [id] => 1 [name] => John Smith  
+
will give (with line breaks added for clarity):</translate>
     [email] => johnsmith@domain.example [username] => johnsmith )  
+
<pre>Array (
[magdah] => stdClass Object ( [id] => 2 [name] => Magda Hellman  
+
[johnsmith] => stdClass Object ( [id] => 1, [name] => John Smith,
     [email] => magda_h@domain.example [username] => magdah )  
+
     [email] => johnsmith@domain.example, [username] => johnsmith ),
[ydegaulle] => stdClass Object ( [id] => 3 [name] => Yvonne de Gaulle  
+
[magdah] => stdClass Object ( [id] => 2, [name] => Magda Hellman,
     [email] => ydg@domain.example [username] => ydegaulle )  
+
     [email] => magda_h@domain.example, [username] => magdah ),
 +
[ydegaulle] => stdClass Object ( [id] => 3, [name] => Yvonne de Gaulle,
 +
     [email] => ydg@domain.example, [username] => ydegaulle )
 
)</pre>
 
)</pre>
  
You can access the individual rows by using:<pre>$row['key_value'] // e.g. $row['johnsmith']</pre>
+
<translate><!--T:124-->
and you can access the individual values by using:<pre>$row['key_value']->column_name // e.g. $row['johnsmith']->email</pre>
+
You can access the individual rows by using:</translate><pre>$row['key_value'] // e.g. $row['johnsmith']</pre>
 +
<translate><!--T:125-->
 +
and you can access the individual values by using:</translate><pre>$row['key_value']->column_name // e.g. $row['johnsmith']->email</pre>
 +
 
 +
<translate><!--T:126-->
 +
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.</translate>
  
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.
+
<translate>
 +
=== Miscellaneous Result Set Methods === <!--T:127-->
 +
</translate>
 +
<translate>
 +
==== getNumRows() ==== <!--T:128-->
 +
</translate>
 +
<translate><!--T:129-->
 +
''getNumRows()'' will return the number of result rows found by the last SELECT or SHOW 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. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use getAffectedRows().</translate>
  
=== Miscellaneous Result Set Methods ===
+
<syntaxhighlight lang='php'>
==== 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. 
 
<source lang='php'>
 
 
. . .
 
. . .
 
$db->setQuery($query);
 
$db->setQuery($query);
Line 412: Line 695:
 
print_r($num_rows);
 
print_r($num_rows);
 
$result = $db->loadRowList();
 
$result = $db->loadRowList();
</source>
+
</syntaxhighlight>
will return <pre>3</pre>
+
 
Note: if you run getNumRows() after loadRowList() - or any other retrieval method - you may get a PHP Warning:
+
<translate><!--T:130-->
<pre>Warning: mysql_num_rows(): 80 is not a valid MySQL result resource  
+
will return</translate> <pre>3</pre>
 +
<translate><!--T:131-->
 +
Note: getNumRows() is only valid for statements like SELECT or SHOW that return an actual result set. If you run getNumRows() after loadRowList() - or any other retrieval method - you will get a PHP Warning:</translate>
 +
<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>
 +
 +
== Sample Module Code ==
 +
Below is the code for a simple Joomla module which you can install and run to demonstrate use of the JDatabase functionality, and which you can adapt to experiment with some of the concepts described above. If you are unsure about development and installing a Joomla module then following the tutorial at [[S:MyLanguage/J3.x:Creating a simple module/Introduction| Creating a simple module ]] will help.
 +
 +
'''Important''' In any Joomla extensions that you develop avoid accessing the core Joomla tables directly like this. Instead use the Joomla APIs. The database structures may change without warning.
 +
 +
In a folder mod_db_select create the following 2 files:
 +
 +
''mod_db_select.xml''
 +
<syntaxhighlight lang="xml">
 +
<?xml version="1.0" encoding="utf-8"?>
 +
<extension type="module" version="3.1" client="site" method="upgrade">
 +
    <name>Database select query demo</name>
 +
    <version>1.0.1</version>
 +
    <description>Code demonstrating use of Joomla Database class to perform SQL SELECT queries</description>
 +
    <files>
 +
        <filename module="mod_db_select">mod_db_select.php</filename>
 +
    </files>
 +
</extension>
 +
</syntaxhighlight>
 +
 +
''mod_db_select.php''
 +
<syntaxhighlight lang="php">
 +
<?php
 +
defined('_JEXEC') or die('Restricted Access');
 +
 +
use Joomla\CMS\Factory;
 +
 +
$db = Factory::getDbo();
 +
 +
$me = Factory::getUser();
 +
 +
$query = $db->getQuery(true);
 +
 +
$query->select($db->quoteName(array('name', 'email')))
 +
->from($db->quoteName('#__users'))
 +
->where($db->quoteName('id') . ' != ' . $db->quote($me->id))
 +
->order($db->quoteName('name') . ' ASC');
 +
 +
$db->setQuery($query);
 +
 +
echo $db->replacePrefix((string) $query);
 +
 +
$results = $db->loadAssocList();
 +
 +
foreach ($results as $row) {
 +
echo "<p>" . $row['name'] . ", " . $row['email'] . "<br></p>";
 +
}
 +
</syntaxhighlight>
 +
 +
The code above selects and outputs the username and email of the records in the Joomla ''users'' table, apart from those of the currently logged-on user. The method ''Factory::getUser()'' returns the ''user'' object of the currently logged-on user, or if not logged on, then a blank ''user'' object, whose ''id'' field is set to zero.
 +
 +
The ''$db->replacePrefix((string) $query)'' expression returns the actual SQL statement, and outputting this can be useful in debugging.
 +
 +
Zip up the mod_db_select directory to create ''mod_db_select.zip''.
 +
 +
Within your Joomla Administrator, go to Install Extensions and via the Upload Package File tab select this zip file to install this sample log module.
 +
 +
Make this module visible by editing it (click on it within the Modules page). Then:
 +
# Make its status ''Published''
 +
# Select a position on the page for it to be shown
 +
# Specify the pages it should appear on in the menu assignment tab
 +
 +
When you visit a site web page, you should see the module in your selected position. It should output the SQL SELECT statement and the sequence of name, email values from the Joomla users table.
 +
 +
<translate>
 +
== See also == <!--T:135-->
 +
</translate>
 +
*[[S:MyLanguage/Inserting, Updating and Removing data using JDatabase|<translate><!--T:136--> Inserting, Updating and Removing data using JDatabase</translate>]]
 +
*[[S:MyLanguage/Using the union methods in database queries|<translate><!--T:137--> Using the union methods in database queries</translate>]] <translate><!--T:138--> (Joomla! 3.3+)</translate>
 +
*[https://api.joomla.org/cms-3/classes/JDatabaseQuery.html <translate><!--T:139--> Joomla CMS 3.8 API</translate>]
 +
 +
<noinclude>
 +
[[Category:Database{{#translation:}}]]
 +
[[Category:JFactory{{#translation:}}]]
 +
[[Category:Extension development{{#translation:}}]]
 +
[[Category:Development Recommended Reading{{#translation:}}]]
 +
[[Category:Tutorials{{#translation:}}]]
 +
</noinclude>

Latest revision as of 16:35, 23 September 2022

Other languages:
English • ‎Nederlands • ‎español • ‎français • ‎русский • ‎中文(中国大陆)‎ • ‎中文(台灣)‎
Joomla! 
3.x
Joomla! 
2.5
Version Note

Note many examples online use $db->query() instead of $db->execute(). This was the old method in Joomla 1.5 and 2.5 and will throw a deprecated notice in Joomla 3.0+.

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. Also see the Inserting, Updating and Removing Data using JDatabase article

Introduction[edit]

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[edit]

Joomla's database querying changed with the introduction of Joomla 1.6. The recommended way of building database queries is through query chaining (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[edit]

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();

(Here the quoteName() function adds appropriate quotes around the column names to avoid conflicts with any database reserved word, now or in the future.)

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 method calls improves code readability and reduces code bloat as 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'));

A limit can be set to a query using setLimit. For example in the following query, it would return up to 10 records.

$query
    ->select($db->quoteName(array('user_id', 'profile_key', 'profile_value', 'ordering')))
    ->from($db->quoteName('#__user_profiles'))
    ->setLimit('10');


Selecting Records from Multiple Tables[edit]

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(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 ' . $db->quote('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(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 ' . $db->quote('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('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 ' . $db->quote('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(array('a.*'))
    ->select($db->quoteName(array('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 ' . $db->quote('a%'))
    ->order($db->quoteName('a.created') . ' DESC');

Using OR in queries[edit]

When using multiple WHERE clauses in your query, they will be treated as an AND.

So, for example, the query below will return results where the 'name' field AND the 'state' field match.

$query = $db
    ->getQuery(true)
    ->select('COUNT(*)')
    ->from($db->quoteName('#__my_table'))
    ->where($db->quoteName('name') . " = " . $db->quote($value)
    ->where($db->quoteName('state') . " = " . $db->quote($state));

To use a WHERE clause as an OR, the query can be written like this

$query = $db
    ->getQuery(true)
    ->select('COUNT(*)')
    ->from($db->quoteName('#__my_table'))
    ->where($db->quoteName('name') . " = " . $db->quote($name_one), 'OR')
    ->where($db->quoteName('name') . " = " . $db->quote($name_two));

it can also be written like this

$query = $db
    ->getQuery(true)
    ->select('COUNT(*)')
    ->from($db->quoteName('#__my_table'))
    ->where($db->quoteName('name') . " = " . $db->quote($name_one)
    ->orWhere($db->quoteName('name') . " = " . $db->quote($name_two));

Query Results[edit]

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

If there are no matches to the query, the result will be null.

Single Value Result[edit]

loadResult()[edit]

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)
    ->select('COUNT(*)')
    ->from($db->quoteName('#__my_table'))
    ->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)
    ->select('field_name')
    ->from($db->quoteName('#__my_table'))
    ->where($db->quoteName('some_name') . " = " . $db->quote($some_value));

$db->setQuery($query);
$result = $db->loadResult();

Single Row Results[edit]

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()[edit]

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()[edit]

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['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.

loadObject()[edit]

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[edit]

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()[edit]

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)[edit]

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[edit]

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()[edit]

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()[edit]

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)[edit]

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.

loadAssocList($key, $column)[edit]

loadAssocList('key', 'column') returns an associative array, indexed on 'key', of values from the column named 'column' returned by the query:

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

will give (with line breaks added for clarity):

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

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()[edit]

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)[edit]

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[edit]

getNumRows()[edit]

getNumRows() will return the number of result rows found by the last SELECT or SHOW 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. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use getAffectedRows().

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

will return

3

Note: getNumRows() is only valid for statements like SELECT or SHOW that return an actual result set. If you run getNumRows() after loadRowList() - or any other retrieval method - you will 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

Sample Module Code[edit]

Below is the code for a simple Joomla module which you can install and run to demonstrate use of the JDatabase functionality, and which you can adapt to experiment with some of the concepts described above. If you are unsure about development and installing a Joomla module then following the tutorial at Creating a simple module will help.

Important In any Joomla extensions that you develop avoid accessing the core Joomla tables directly like this. Instead use the Joomla APIs. The database structures may change without warning.

In a folder mod_db_select create the following 2 files:

mod_db_select.xml

<?xml version="1.0" encoding="utf-8"?>
<extension type="module" version="3.1" client="site" method="upgrade">
    <name>Database select query demo</name>
    <version>1.0.1</version>
    <description>Code demonstrating use of Joomla Database class to perform SQL SELECT queries</description>
    <files>
        <filename module="mod_db_select">mod_db_select.php</filename>
    </files>
</extension>

mod_db_select.php

<?php
defined('_JEXEC') or die('Restricted Access');

use Joomla\CMS\Factory;

$db = Factory::getDbo();

$me = Factory::getUser();

$query = $db->getQuery(true);

$query->select($db->quoteName(array('name', 'email')))
	->from($db->quoteName('#__users'))
	->where($db->quoteName('id') . ' != ' . $db->quote($me->id))
	->order($db->quoteName('name') . ' ASC');

$db->setQuery($query);

echo $db->replacePrefix((string) $query);

$results = $db->loadAssocList();

foreach ($results as $row) {
	echo "<p>" . $row['name'] . ", " . $row['email'] . "<br></p>";
}

The code above selects and outputs the username and email of the records in the Joomla users table, apart from those of the currently logged-on user. The method Factory::getUser() returns the user object of the currently logged-on user, or if not logged on, then a blank user object, whose id field is set to zero.

The $db->replacePrefix((string) $query) expression returns the actual SQL statement, and outputting this can be useful in debugging.

Zip up the mod_db_select directory to create mod_db_select.zip.

Within your Joomla Administrator, go to Install Extensions and via the Upload Package File tab select this zip file to install this sample log module.

Make this module visible by editing it (click on it within the Modules page). Then:

  1. Make its status Published
  2. Select a position on the page for it to be shown
  3. Specify the pages it should appear on in the menu assignment tab

When you visit a site web page, you should see the module in your selected position. It should output the SQL SELECT statement and the sequence of name, email values from the Joomla users table.

See also[edit]