J4.x

Difference between revisions of "Selecting data using JDatabase"

From Joomla! Documentation

m (Excess </pre>)
 
(4 intermediate revisions by 4 users not shown)
Line 3: Line 3:
 
{{-}}
 
{{-}}
 
{{tip|<translate><!--T:1-->
 
{{tip|<translate><!--T:1-->
Note many examples online do not use the prepared statements methods that have been introduced with Joomla 4.x, please do not use these old APIs for new projects, because they result in massive security issues if user input is not strictly escaped.</translate>|title=<translate><!--T:2-->
+
Note that many examples online do not use the prepared statements methods that have been introduced with Joomla 4.x. Please do not use these old APIs for new projects. They result in massive security issues if user input is not strictly escaped.</translate>|title=<translate><!--T:2-->
 
Version Note</translate>}}
 
Version Note</translate>}}
  
Line 37: Line 37:
 
To obtain a new instance of the \Joomla\Database\DatabaseQuery class we use the \Joomla\Database\DatabaseDriver getQuery method:</translate>
 
To obtain a new instance of the \Joomla\Database\DatabaseQuery class we use the \Joomla\Database\DatabaseDriver getQuery method:</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
use Joomla\CMS\Factory;
 
use Joomla\CMS\Factory;
  
$db = Factory::getDbo();
+
// When used in the component's Model
 +
$db = $this->getDatabase();
 +
 
 +
// When used in other places
 +
$db = Factory::getContainer()->get('DatabaseDriver');
  
 
$query = $db->getQuery(true);
 
$query = $db->getQuery(true);
</source>
+
</syntaxhighlight>
 +
 
 +
Do NOT use the following Joomla 3 method anymore because it is deprecated:
 +
 
 +
<del>$db = Factory::getDbo();</del>
 +
 
  
 
<translate><!--T:14-->
 
<translate><!--T:14-->
Line 49: Line 58:
  
 
<translate><!--T:15-->
 
<translate><!--T:15-->
To query our data source we can call a number of \Joomla\Database\DatabaseQuery 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>  
+
To query our data source we can call a number of \Joomla\Database\DatabaseQuery 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>
  
 
<translate><!--T:16-->
 
<translate><!--T:16-->
Line 61: Line 70:
 
Below is an example of creating a database query using the <tt>\Joomla\Database\DatabaseQuery</tt> class. Using the select, from, where and order methods, we can create queries which are flexible, easily readable and portable:</translate>
 
Below is an example of creating a database query using the <tt>\Joomla\Database\DatabaseQuery</tt> 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">
 
use Joomla\CMS\Factory;
 
use Joomla\CMS\Factory;
  
 
// Get a db connection.
 
// Get a db connection.
$db = Factory::getDbo();
+
$db = Factory::getContainer()->get('DatabaseDriver');
  
 
// Create a new query object.
 
// Create a new query object.
Line 85: Line 94:
 
// 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:19-->
 
<translate><!--T:19-->
 
The query can also be chained to simplify further:</translate>
 
The query can also be chained to simplify further:</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
$query
 
$query
 
     ->select($db->quoteName(['user_id', 'profile_key', 'profile_value', 'ordering']))
 
     ->select($db->quoteName(['user_id', 'profile_key', 'profile_value', 'ordering']))
Line 97: Line 106:
 
     ->order($db->quoteName('ordering') . ' ASC')
 
     ->order($db->quoteName('ordering') . ' ASC')
 
     ->bind(':profile_key', 'custom.%');
 
     ->bind(':profile_key', 'custom.%');
</source>
+
</syntaxhighlight>
  
 
<translate><!--T:20-->
 
<translate><!--T:20-->
Line 103: Line 112:
  
 
<translate><!--T:21-->
 
<translate><!--T:21-->
Grouping can be achieved simply too. The following query would count the number of articles in each category.</translate>
+
Grouping can be achieved simply too. The following query would count the number of articles in each category.</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
$query
 
$query
 
     ->select( ['catid', 'COUNT(*)'] )
 
     ->select( ['catid', 'COUNT(*)'] )
 
     ->from($db->quoteName('#__content'))
 
     ->from($db->quoteName('#__content'))
 
     ->group($db->quoteName('catid'));
 
     ->group($db->quoteName('catid'));
</source>
+
</syntaxhighlight>
  
 
<translate><!--T:22-->
 
<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>
 
A limit can be set to a query using "setLimit". For example in the following query, it would return up to 10 records.</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
$query
 
$query
 
     ->select($db->quoteName(['user_id', 'profile_key', 'profile_value', 'ordering']))
 
     ->select($db->quoteName(['user_id', 'profile_key', 'profile_value', 'ordering']))
 
     ->from($db->quoteName('#__user_profiles'))
 
     ->from($db->quoteName('#__user_profiles'))
 
     ->setLimit('10');
 
     ->setLimit('10');
</source>
+
</syntaxhighlight>
  
 
<translate>
 
<translate>
 
 
==Selecting Records from Multiple Tables== <!--T:23-->
 
==Selecting Records from Multiple Tables== <!--T:23-->
 
</translate>
 
</translate>
 
<translate><!--T:24-->
 
<translate><!--T:24-->
Using the \Joomla\Database\DatabaseQuery's [https://api.joomla.org/framework-1/classes/Joomla.Database.DatabaseQuery.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).</translate>
+
Using the \Joomla\Database\DatabaseQuery's [https://api.joomla.org/framework-1/classes/Joomla-Database-DatabaseQuery.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).</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
use Joomla\CMS\Factory;
 
use Joomla\CMS\Factory;
  
 
// Get a db connection.
 
// Get a db connection.
$db = Factory::getDbo();
+
$db = Factory::getContainer()->get('DatabaseDriver');
  
 
// Create a new query object.
 
// Create a new query object.
Line 154: Line 162:
 
// 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-->
 
<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>
 
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/framework-1/classes/Joomla.Database.DatabaseQuery.html#method_innerJoin innerJoin()]
+
* [https://api.joomla.org/framework-1/classes/Joomla-Database-DatabaseQuery.html#method_innerJoin innerJoin()]
* [https://api.joomla.org/framework-1/classes/Joomla.Database.DatabaseQuery.html#method_leftJoin leftJoin()]
+
* [https://api.joomla.org/framework-1/classes/Joomla-Database-DatabaseQuery.html#method_leftJoin leftJoin()]
* [https://api.joomla.org/framework-1/classes/Joomla.Database.DatabaseQuery.html#method_rightJoin rightJoin()]  
+
* [https://api.joomla.org/framework-1/classes/Joomla-Database-DatabaseQuery.html#method_rightJoin rightJoin()]
* [https://api.joomla.org/framework-1/classes/Joomla.Database.DatabaseQuery.html#method_outerJoin outerJoin()]
+
* [https://api.joomla.org/framework-1/classes/Joomla-Database-DatabaseQuery.html#method_outerJoin outerJoin()]
  
 
<translate><!--T:26-->
 
<translate><!--T:26-->
 
We can use multiple joins to query across more than two tables:</translate>
 
We can use multiple joins to query across more than two tables:</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
$query
 
$query
 
     ->select(array('a.*', 'b.username', 'b.name', 'c.*', 'd.*'))
 
     ->select(array('a.*', 'b.username', 'b.name', 'c.*', 'd.*'))
Line 176: Line 184:
 
     ->order($db->quoteName('a.created') . ' DESC')
 
     ->order($db->quoteName('a.created') . ' DESC')
 
     ->bind(':username', 'a%');
 
     ->bind(':username', 'a%');
</source>
+
</syntaxhighlight>
  
 
<translate><!--T:27-->
 
<translate><!--T:27-->
Notice how chaining makes the source code much more readable for these longer queries.</translate>
+
Notice how chaining makes the source code more readable for these longer queries.</translate>
  
 
<translate><!--T:28-->
 
<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>
 
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>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
$query
 
$query
 
     ->select('a.*')
 
     ->select('a.*')
Line 194: Line 202:
 
     ->order($db->quoteName('a.created') . ' DESC')
 
     ->order($db->quoteName('a.created') . ' DESC')
 
     ->bind(':username', 'a%');
 
     ->bind(':username', 'a%');
</source>
+
</syntaxhighlight>
  
 
<translate><!--T:29-->
 
<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>
 
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(['a.*'])
 
     ->select(['a.*'])
Line 208: Line 216:
 
     ->order($db->quoteName('a.created') . ' DESC')
 
     ->order($db->quoteName('a.created') . ' DESC')
 
     ->bind(':username', 'a%');
 
     ->bind(':username', 'a%');
</source>
+
</syntaxhighlight>
  
 
<translate>
 
<translate>
==Using prepared statements== <!--T:140--> </translate>
+
==Using Prepared Statements== <!--T:140--> </translate>
 
<translate>
 
<translate>
 
<!--T:141-->
 
<!--T:141-->
Line 219: Line 227:
 
Simple query with prepared statements.</translate>
 
Simple query with prepared statements.</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
$query = $this->db->getQuery(true)
 
$query = $this->db->getQuery(true)
 
->select($this->db->quoteName(array('id', 'password')))
 
->select($this->db->quoteName(array('id', 'password')))
Line 225: Line 233:
 
->where($this->db->quoteName('username') . ' = :username')
 
->where($this->db->quoteName('username') . ' = :username')
 
->bind(':username', $credentials['username']);
 
->bind(':username', $credentials['username']);
</source>
+
</syntaxhighlight>
 
<translate>
 
<translate>
 
<!--T:143-->
 
<!--T:143-->
Line 233: Line 241:
 
Beware that binding a variable will always be a reference. A nice side effect of this, is that you can manipulate the query in a loop.</translate>
 
Beware that binding a variable will always be a reference. A nice side effect of this, is that you can manipulate the query in a loop.</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
  
 
$listOfUsernames = [ 'admin', 'user1' ];
 
$listOfUsernames = [ 'admin', 'user1' ];
Line 250: Line 258:
 
   print_r($user);
 
   print_r($user);
 
}
 
}
</source>
+
</syntaxhighlight>
 
<translate>
 
<translate>
 
<!--T:145-->
 
<!--T:145-->
In the loop we set the previously bound $username variable with the $name variable from the loop, then we have to set the query again (because Joomla reset the database driver after query execution which is only true for load* functions).
+
In the loop we set the previously bound $username variable with the $name variable from the loop, then we have to set the query again (because Joomla resets the database driver after query execution which is only true for load* functions).
The result of this will be multiple queries with different username values.</translate>
+
The result will be multiple queries with different username values.</translate>
 
<translate>
 
<translate>
 
<!--T:146-->
 
<!--T:146-->
 
We can use arrays to add multiple variables at once.</translate>
 
We can use arrays to add multiple variables at once.</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
$query = $this->db->getQuery(true)
 
$query = $this->db->getQuery(true)
 
->select($this->db->quoteName(array('id', 'password')))
 
->select($this->db->quoteName(array('id', 'password')))
Line 266: Line 274:
 
->where($this->db->quoteName('id') . ' = :id')
 
->where($this->db->quoteName('id') . ' = :id')
 
->bind([':username', ':id'], [$credentials['username'], 42], [Joomla\Database\ParameterType::STRING, Joomla\Database\ParameterType::INTEGER]);
 
->bind([':username', ':id'], [$credentials['username'], 42], [Joomla\Database\ParameterType::STRING, Joomla\Database\ParameterType::INTEGER]);
</source>
+
</syntaxhighlight>
 
<translate>
 
<translate>
 
<!--T:147-->
 
<!--T:147-->
Line 272: Line 280:
 
It's also possible to use one variable for all bind values and ParameterTypes.</translate>
 
It's also possible to use one variable for all bind values and ParameterTypes.</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
$query = $this->db->getQuery(true)
 
$query = $this->db->getQuery(true)
 
->select($this->db->quoteName(array('id', 'password')))
 
->select($this->db->quoteName(array('id', 'password')))
Line 278: Line 286:
 
->where($this->db->quoteName('username') . ' = :username')
 
->where($this->db->quoteName('username') . ' = :username')
 
->where($this->db->quoteName('password') . ' = :password')
 
->where($this->db->quoteName('password') . ' = :password')
->bind([':username', ':password], $credentials['username']);
+
->bind([':username', ':password'], $credentials['username']);
</source>
+
</syntaxhighlight>
 
<translate>
 
<translate>
 
<!--T:148-->
 
<!--T:148-->
Line 287: Line 295:
 
The function '''whereIn()''' and '''whereNotIn()''' always use prepared statements, internal these functions uses the '''bindArray''' function. It can be used to bind an array of variables without specifying the placeholder.</translate>
 
The function '''whereIn()''' and '''whereNotIn()''' always use prepared statements, internal these functions uses the '''bindArray''' function. It can be used to bind an array of variables without specifying the placeholder.</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
$userids = [1,2,3,4];
 
$userids = [1,2,3,4];
  
Line 297: Line 305:
  
 
$query->where($this->db->quoteName('id') . ' IN (' . implode(',', $parameterNames) . ')');
 
$query->where($this->db->quoteName('id') . ' IN (' . implode(',', $parameterNames) . ')');
</source>
+
</syntaxhighlight>
  
 
The '''bindArray''' function returns an array of placeholders. The index is unique for the whole query.
 
The '''bindArray''' function returns an array of placeholders. The index is unique for the whole query.
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
$placeholders = [
 
$placeholders = [
 
   ':preparedArray1',
 
   ':preparedArray1',
Line 308: Line 316:
 
   ':preparedArray4'
 
   ':preparedArray4'
 
];
 
];
</source>
+
</syntaxhighlight>
  
 
<translate>
 
<translate>
 +
 
==Query Results == <!--T:30-->
 
==Query Results == <!--T:30-->
 
</translate>
 
</translate>
Line 323: Line 332:
 
</translate>
 
</translate>
 
<translate><!--T:34-->
 
<translate><!--T:34-->
Use '''loadResult()''' when you expect just a single value back from your database query.</translate>  
+
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"
Line 332: Line 341:
 
email</translate> !! <translate><!--T:38-->
 
email</translate> !! <translate><!--T:38-->
 
username</translate>
 
username</translate>
|-  
+
|-
 
| 1 || style="background:yellow" | John Smith || <translate><!--T:39-->
 
| 1 || style="background:yellow" | John Smith || <translate><!--T:39-->
 
johnsmith@domain.example</translate> || johnsmith
 
johnsmith@domain.example</translate> || johnsmith
Line 344: Line 353:
  
 
<translate><!--T:42-->
 
<translate><!--T:42-->
This is often the result of a 'count' query to get a number of records:</translate>
+
This is often the result of a 'count' query to get the number of records:</translate>
  
<source lang="php">
+
<syntaxhighlight lang="php">
 
use Joomla\CMS\Factory;
 
use Joomla\CMS\Factory;
$db = Factory::getDbo();
+
$db = Factory::getContainer()->get('DatabaseDriver');
 
$query = $db->getQuery(true);
 
$query = $db->getQuery(true);
 
$query->select('COUNT(*)');
 
$query->select('COUNT(*)');
Line 358: Line 367:
 
$db->setQuery($query);
 
$db->setQuery($query);
 
$count = $db->loadResult();
 
$count = $db->loadResult();
</source>
+
</syntaxhighlight>
 
<translate><!--T:134-->
 
<translate><!--T:134-->
 
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>
 
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>
<source lang='php'>
+
<syntaxhighlight lang='php'>
 
use Joomla\CMS\Factory;
 
use Joomla\CMS\Factory;
$db = Factory::getDbo();
+
$db = Factory::getContainer()->get('DatabaseDriver');
 
$query = $db->getQuery(true);
 
$query = $db->getQuery(true);
 
$query->select('field_name');
 
$query->select('field_name');
Line 372: Line 381:
 
$db->setQuery($query);
 
$db->setQuery($query);
 
$result = $db->loadResult();
 
$result = $db->loadResult();
</source>
+
</syntaxhighlight>
  
 
<translate>
 
<translate>
Line 378: Line 387:
 
</translate>
 
</translate>
 
<translate><!--T:44-->
 
<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>
+
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>
  
 
{| class="wikitable" style="text-align:center"
 
{| class="wikitable" style="text-align:center"
Line 402: Line 411:
 
</translate>
 
</translate>
 
<translate><!--T:53-->
 
<translate><!--T:53-->
<tt>loadRow()</tt> returns an indexed array from a single record in the table:</translate>  
+
<tt>loadRow()</tt> returns an indexed array from a single record in the table:</translate>
  
<source lang='php'>
+
<syntaxhighlight lang='php'>
 
. . .
 
. . .
 
$db->setQuery($query);
 
$db->setQuery($query);
 
$row = $db->loadRow();
 
$row = $db->loadRow();
 
print_r($row);
 
print_r($row);
</source>
+
</syntaxhighlight>
 
<translate><!--T:133-->
 
<translate><!--T:133-->
 
will give:</translate>
 
will give:</translate>
Line 430: Line 439:
 
<tt>loadAssoc()</tt> returns an associated array from a single record in the table:</translate>
 
<tt>loadAssoc()</tt> returns an associated array from a single record in the table:</translate>
  
<source lang='php'>
+
<syntaxhighlight 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-->
 
<translate><!--T:60-->
Line 454: Line 463:
 
loadObject returns a PHP object from a single record in the table:</translate>
 
loadObject returns a PHP object from a single record in the table:</translate>
  
<source lang='php'>
+
<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-->
 
<translate><!--T:65-->
Line 476: Line 485:
 
</translate>
 
</translate>
 
<translate><!--T:69-->
 
<translate><!--T:69-->
Each of these results functions will return a single column from the database.</translate>  
+
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"
Line 485: Line 494:
 
email</translate> !! <translate><!--T:73-->
 
email</translate> !! <translate><!--T:73-->
 
username</translate>
 
username</translate>
|-  
+
|-
 
| 1 || style="background:yellow" | John Smith || <translate><!--T:74-->
 
| 1 || style="background:yellow" | John Smith || <translate><!--T:74-->
 
johnsmith@domain.example</translate> || johnsmith
 
johnsmith@domain.example</translate> || johnsmith
Line 502: Line 511:
 
<tt>loadColumn()</tt> returns an indexed array from a single column in the table:</translate>
 
<tt>loadColumn()</tt> returns an indexed array from a single column in the table:</translate>
  
<source lang='php'>
+
<syntaxhighlight lang='php'>
 
$query->select('name'));
 
$query->select('name'));
 
       ->from . . .";
 
       ->from . . .";
Line 509: Line 518:
 
$column= $db->loadColumn();
 
$column= $db->loadColumn();
 
print_r($column);
 
print_r($column);
</source>
+
</syntaxhighlight>
  
 
<translate><!--T:79-->
 
<translate><!--T:79-->
Line 529: Line 538:
 
loadColumn($index) returns an indexed array from a single column in the table:</translate>
 
loadColumn($index) returns an indexed array from a single column in the table:</translate>
  
<source lang='php'>
+
<syntaxhighlight lang='php'>
 
$query->select(array('name', 'email', 'username'));
 
$query->select(array('name', 'email', 'username'));
 
       ->from . . .";
 
       ->from . . .";
Line 536: Line 545:
 
$column= $db->loadColumn(1);
 
$column= $db->loadColumn(1);
 
print_r($column);
 
print_r($column);
</source>
+
</syntaxhighlight>
  
 
<translate><!--T:84-->
 
<translate><!--T:84-->
Line 546: Line 555:
  
 
<translate><!--T:86-->
 
<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:</translate>
  
<source lang='php'>
+
<syntaxhighlight lang='php'>
 
. . .
 
. . .
 
$db->setQuery($query);
 
$db->setQuery($query);
Line 555: Line 564:
 
   print_r($column);
 
   print_r($column);
 
}
 
}
</source>
+
</syntaxhighlight>
  
 
<translate><!--T:87-->
 
<translate><!--T:87-->
Line 571: Line 580:
 
</translate>
 
</translate>
 
<translate><!--T:90-->
 
<translate><!--T:90-->
Each of these results functions will return multiple records from the database.</translate>  
+
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"
Line 594: Line 603:
 
<tt>loadRowList()</tt> returns an indexed array of indexed arrays from the table records returned by the query:</translate>
 
<tt>loadRowList()</tt> returns an indexed array of indexed arrays from the table records returned by the query:</translate>
  
<source lang='php'>
+
<syntaxhighlight lang='php'>
 
. . .
 
. . .
 
$db->setQuery($query);
 
$db->setQuery($query);
 
$row = $db->loadRowList();
 
$row = $db->loadRowList();
 
print_r($row);
 
print_r($row);
</source>
+
</syntaxhighlight>
  
 
<translate><!--T:97-->
 
<translate><!--T:97-->
 
will give (with line breaks added for clarity):</translate>
 
will give (with line breaks added for clarity):</translate>
  
<pre>Array (  
+
<pre>Array (
[0] => Array ( [0] => 1, [1] => John Smith, [2] => johnsmith@domain.example, [3] => johnsmith ),  
+
[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 ),  
+
[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 )  
+
[2] => Array ( [0] => 3, [1] => Yvonne de Gaulle, [2] => ydg@domain.example, [3] => ydegaulle )
 
)</pre>
 
)</pre>
  
Line 623: Line 632:
 
<tt>loadAssocList()</tt> returns an indexed array of associated arrays from the table records returned by the query:</translate>
 
<tt>loadAssocList()</tt> returns an indexed array of associated arrays from the table records returned by the query:</translate>
  
<source lang='php'>
+
<syntaxhighlight lang='php'>
 
. . .
 
. . .
 
$db->setQuery($query);
 
$db->setQuery($query);
 
$row = $db->loadAssocList();
 
$row = $db->loadAssocList();
 
print_r($row);
 
print_r($row);
</source>
+
</syntaxhighlight>
  
 
<translate><!--T:103-->
 
<translate><!--T:103-->
 
will give (with line breaks added for clarity):</translate>
 
will give (with line breaks added for clarity):</translate>
<pre>Array (  
+
<pre>Array (
[0] => Array ( [id] => 1, [name] => John Smith, [email] => johnsmith@domain.example, [username] => johnsmith ),  
+
[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 ),  
+
[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 )  
+
[2] => Array ( [id] => 3, [name] => Yvonne de Gaulle, [email] => ydg@domain.example, [username] => ydegaulle )
 
) </pre>
 
) </pre>
  
Line 647: Line 656:
 
<tt>loadAssocList('key')</tt> returns an associated array - indexed on 'key' - of associated arrays from the table records returned by the query:</translate>
 
<tt>loadAssocList('key')</tt> returns an associated array - indexed on 'key' - of associated arrays from the table records returned by the query:</translate>
  
<source lang='php'>
+
<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>
  
 
<translate><!--T:108-->
 
<translate><!--T:108-->
 
will give (with line breaks added for clarity):</translate>
 
will give (with line breaks added for clarity):</translate>
<pre>Array (  
+
<pre>Array (
[johnsmith] => Array ( [id] => 1, [name] => John Smith, [email] => johnsmith@domain.example, [username] => johnsmith ),  
+
[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 ),  
+
[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 )  
+
[ydegaulle] => Array ( [id] => 3, [name] => Yvonne de Gaulle, [email] => ydg@domain.example, [username] => ydegaulle )
 
)</pre>
 
)</pre>
  
Line 674: Line 683:
 
<tt>loadAssocList('key', 'column')</tt> returns an associative array, indexed on 'key', of values from the column named 'column' returned by the query:</translate>
 
<tt>loadAssocList('key', 'column')</tt> returns an associative array, indexed on 'key', of values from the column named 'column' returned by the query:</translate>
  
<source lang='php'>
+
<syntaxhighlight lang='php'>
 
. . .
 
. . .
 
$db->setQuery($query);
 
$db->setQuery($query);
 
$row = $db->loadAssocList('id', 'username');
 
$row = $db->loadAssocList('id', 'username');
 
print_r($row);
 
print_r($row);
</source>
+
</syntaxhighlight>
  
 
<translate><!--T:114-->
 
<translate><!--T:114-->
 
will give (with line breaks added for clarity):</translate>
 
will give (with line breaks added for clarity):</translate>
<pre>Array (  
+
<pre>Array (
[1] => John Smith,  
+
[1] => John Smith,
[2] => Magda Hellman,  
+
[2] => Magda Hellman,
 
[3] => Yvonne de Gaulle,
 
[3] => Yvonne de Gaulle,
 
)</pre>
 
)</pre>
Line 696: Line 705:
 
<tt>loadObjectList()</tt> returns an indexed array of PHP objects from the table records returned by the query:</translate>
 
<tt>loadObjectList()</tt> returns an indexed array of PHP objects from the table records returned by the query:</translate>
  
<source lang='php'>
+
<syntaxhighlight lang='php'>
 
. . .
 
. . .
 
$db->setQuery($query);
 
$db->setQuery($query);
 
$row = $db->loadObjectList();
 
$row = $db->loadObjectList();
 
print_r($row);
 
print_r($row);
</source>
+
</syntaxhighlight>
  
 
<translate><!--T:118-->
 
<translate><!--T:118-->
 
will give (with line breaks added for clarity):</translate>
 
will give (with line breaks added for clarity):</translate>
<pre>Array (  
+
<pre>Array (
[0] => stdClass Object ( [id] => 1, [name] => John Smith,  
+
[0] => stdClass Object ( [id] => 1, [name] => John Smith,
     [email] => johnsmith@domain.example, [username] => johnsmith ),  
+
     [email] => johnsmith@domain.example, [username] => johnsmith ),
[1] => stdClass Object ( [id] => 2, [name] => Magda Hellman,  
+
[1] => stdClass Object ( [id] => 2, [name] => Magda Hellman,
     [email] => magda_h@domain.example, [username] => magdah ),  
+
     [email] => magda_h@domain.example, [username] => magdah ),
[2] => stdClass Object ( [id] => 3, [name] => Yvonne de Gaulle,  
+
[2] => stdClass Object ( [id] => 3, [name] => Yvonne de Gaulle,
     [email] => ydg@domain.example, [username] => ydegaulle )  
+
     [email] => ydg@domain.example, [username] => ydegaulle )
 
)</pre>
 
)</pre>
  
Line 723: Line 732:
 
<tt>loadObjectList('key')</tt> returns an associated array - indexed on 'key' - of objects from the table records returned by the query:</translate>
 
<tt>loadObjectList('key')</tt> returns an associated array - indexed on 'key' - of objects from the table records returned by the query:</translate>
  
<source lang='php'>
+
<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>
  
 
<translate><!--T:123-->
 
<translate><!--T:123-->
 
will give (with line breaks added for clarity):</translate>
 
will give (with line breaks added for clarity):</translate>
<pre>Array (  
+
<pre>Array (
[johnsmith] => stdClass Object ( [id] => 1, [name] => John Smith,  
+
[johnsmith] => stdClass Object ( [id] => 1, [name] => John Smith,
     [email] => johnsmith@domain.example, [username] => johnsmith ),  
+
     [email] => johnsmith@domain.example, [username] => johnsmith ),
[magdah] => stdClass Object ( [id] => 2, [name] => Magda Hellman,  
+
[magdah] => stdClass Object ( [id] => 2, [name] => Magda Hellman,
     [email] => magda_h@domain.example, [username] => magdah ),  
+
     [email] => magda_h@domain.example, [username] => magdah ),
[ydegaulle] => stdClass Object ( [id] => 3, [name] => Yvonne de Gaulle,  
+
[ydegaulle] => stdClass Object ( [id] => 3, [name] => Yvonne de Gaulle,
     [email] => ydg@domain.example, [username] => ydegaulle )  
+
     [email] => ydg@domain.example, [username] => ydegaulle )
 
)</pre>
 
)</pre>
  
Line 757: Line 766:
 
<translate><!--T:129-->
 
<translate><!--T:129-->
 
<tt>getNumRows()</tt> 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>
 
<tt>getNumRows()</tt> 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>
+
 
<source lang='php'>
+
<syntaxhighlight lang='php'>
 
. . .
 
. . .
 
$db->setQuery($query);
 
$db->setQuery($query);
Line 765: Line 774:
 
print_r($num_rows);
 
print_r($num_rows);
 
$result = $db->loadRowList();
 
$result = $db->loadRowList();
</source>
+
</syntaxhighlight>
  
 
<translate><!--T:130-->
 
<translate><!--T:130-->
Line 771: Line 780:
 
<translate><!--T:131-->
 
<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>
 
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  
+
<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>
  
 
<translate>
 
<translate>
=== See also === <!--T:135-->
+
=== See Also === <!--T:135-->
 
</translate>
 
</translate>
 +
*[https://manual.joomla.org/docs/next/security/secure-db-queries/ Joomla! Programmers Documentation: Secure DB Queries]
 
*[[S:MyLanguage/J4.x:Inserting, Updating and Removing data using JDatabase|<translate><!--T:136--> Inserting, Updating and Removing data using JDatabase</translate>]]
 
*[[S:MyLanguage/J4.x:Inserting, Updating and Removing data using JDatabase|<translate><!--T:136--> Inserting, Updating and Removing data using JDatabase</translate>]]
 
*[[S:MyLanguage/J4.x:Moving_Joomla_To_Prepared_Statements|<translate><!--T:151--> Moving Joomla To Prepared Statements</translate>]]
 
*[[S:MyLanguage/J4.x:Moving_Joomla_To_Prepared_Statements|<translate><!--T:151--> Moving Joomla To Prepared Statements</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>
 
*[[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://php.net/manual/en/pdo.prepared-statements.php <translate><!--T:152--> The PHP Manual on Prepared statements</translate>]
 
*[https://php.net/manual/en/pdo.prepared-statements.php <translate><!--T:152--> The PHP Manual on Prepared statements</translate>]
*[https://api.joomla.org/framework-1/classes/Joomla.Database.DatabaseQuery.html <translate><!--T:139--> Joomla Framework API</translate>]  
+
*[https://api.joomla.org/framework-1/classes/Joomla-Database-DatabaseQuery.html <translate><!--T:139--> Joomla Framework API</translate>]
  
 
<noinclude>
 
<noinclude>

Latest revision as of 15:52, 24 February 2024

Other languages:
Deutsch • ‎English • ‎español • ‎français
Joomla! 
4.x
Version Note

Note that many examples online do not use the prepared statements methods that have been introduced with Joomla 4.x. Please do not use these old APIs for new projects. They result in massive security issues if user input is not strictly escaped.

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

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]

Since Joomla introduced support for a variety of database types in Joomla 1.6 - the recommended way of building database queries is through "query chaining" (although string queries will always be 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 \Joomla\Database\DatabaseQuery class we use the \Joomla\Database\DatabaseDriver getQuery method:

use Joomla\CMS\Factory;

// When used in the component's Model
$db = $this->getDatabase();

// When used in other places 
$db = Factory::getContainer()->get('DatabaseDriver');

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

Do NOT use the following Joomla 3 method anymore because it is deprecated:

$db = Factory::getDbo();


The \Joomla\Database\DatabaseDriver::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 \Joomla\Database\DatabaseQuery 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 \Joomla\Database\DatabaseQuery class. Using the select, from, where and order methods, we can create queries which are flexible, easily readable and portable:

use Joomla\CMS\Factory;

// Get a db connection.
$db = Factory::getContainer()->get('DatabaseDriver');

// 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(['user_id', 'profile_key', 'profile_value', 'ordering']));
$query->from($db->quoteName('#__user_profiles'));
$query->where($db->quoteName('profile_key') . ' LIKE :profile_key');
$query->order($db->quoteName('ordering') . ' ASC');

// bind value for prepared statements
$query->bind(':profile_key', 'custom.%');

// 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(['user_id', 'profile_key', 'profile_value', 'ordering']))
    ->from($db->quoteName('#__user_profiles'))
    ->where($db->quoteName('profile_key') . ' LIKE :profile_key')
    ->order($db->quoteName('ordering') . ' ASC')
    ->bind(':profile_key', 'custom.%');

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( ['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(['user_id', 'profile_key', 'profile_value', 'ordering']))
    ->from($db->quoteName('#__user_profiles'))
    ->setLimit('10');

Selecting Records from Multiple Tables[edit]

Using the \Joomla\Database\DatabaseQuery'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).

use Joomla\CMS\Factory;

// Get a db connection.
$db = Factory::getContainer()->get('DatabaseDriver');

// 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(['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 :username')
    ->order($db->quoteName('a.created') . ' DESC')
    ->bind(':username', 'a%');

// 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 :username')
    ->order($db->quoteName('a.created') . ' DESC')
    ->bind(':username', 'a%');

Notice how chaining makes the source code 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'), $db->quoteName('a.created_by') . ' = ' . $db->quoteName('b.id'))
    ->where($db->quoteName('b.username') . ' LIKE :username')
    ->order($db->quoteName('a.created') . ' DESC')
    ->bind(':username', 'a%');

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(['a.*'])
    ->select($db->quoteName(array('b.username', 'b.name'), ['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 :username')
    ->order($db->quoteName('a.created') . ' DESC')
    ->bind(':username', 'a%');

Using Prepared Statements[edit]

With Joomla! 4.0 we have moved all queries to use prepared statements. For easier use of prepared statements we introduced some helper functions and allow to use arrays in several function calls. Simple query with prepared statements.

$query = $this->db->getQuery(true)
	->select($this->db->quoteName(array('id', 'password')))
	->from($this->db->quoteName('#__users'))
	->where($this->db->quoteName('username') . ' = :username')
	->bind(':username', $credentials['username']);

You see that we don't add the $credentials['username'] directly to the query, instead we add the placeholder :username into the query and bind the variable to the query. When we bind a variable to a query we don't need to escape nor to quote it. Beware that binding a variable will always be a reference. A nice side effect of this, is that you can manipulate the query in a loop.

$listOfUsernames = [ 'admin', 'user1' ];

$query = $this->db->getQuery(true)
	->select($this->db->quoteName(array('id', 'password')))
	->from($this->db->quoteName('#__users'))
	->where($this->db->quoteName('username') . ' = :username')
	->bind(':username', $username);

foreach($listOfUsernames as $name)
{
  $username = $name;
  $this->db->setQuery($query);
  $user = $this->db->loadObject();
  print_r($user);
}

In the loop we set the previously bound $username variable with the $name variable from the loop, then we have to set the query again (because Joomla resets the database driver after query execution which is only true for load* functions). The result will be multiple queries with different username values. We can use arrays to add multiple variables at once.

$query = $this->db->getQuery(true)
	->select($this->db->quoteName(array('id', 'password')))
	->from($this->db->quoteName('#__users'))
	->where($this->db->quoteName('username') . ' = :username')
	->where($this->db->quoteName('id') . ' = :id')
	->bind([':username', ':id'], [$credentials['username'], 42], [Joomla\Database\ParameterType::STRING, Joomla\Database\ParameterType::INTEGER]);

We add username and id as bind parameter and set the correct ParameterType for each variable. It's also possible to use one variable for all bind values and ParameterTypes.

$query = $this->db->getQuery(true)
	->select($this->db->quoteName(array('id', 'password')))
	->from($this->db->quoteName('#__users'))
	->where($this->db->quoteName('username') . ' = :username')
	->where($this->db->quoteName('password') . ' = :password')
	->bind([':username', ':password'], $credentials['username']);

The parameter :username and :password get set to the same value and the default ParameterType. The function whereIn() and whereNotIn() always use prepared statements, internal these functions uses the bindArray function. It can be used to bind an array of variables without specifying the placeholder.

$userids = [1,2,3,4];

$query = $this->db->getQuery(true)
	->select($this->db->quoteName(array('id', 'password')))
	->from($this->db->quoteName('#__users'));

$parameterNames = $query->bindArray($userids);

$query->where($this->db->quoteName('id') . ' IN (' . implode(',', $parameterNames) . ')');

The bindArray function returns an array of placeholders. The index is unique for the whole query.

$placeholders = [
  ':preparedArray1',
  ':preparedArray2',
  ':preparedArray3',
  ':preparedArray4'
];


Query Results[edit]

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

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 the number of records:

use Joomla\CMS\Factory;
$db = Factory::getContainer()->get('DatabaseDriver');
$query = $db->getQuery(true);
$query->select('COUNT(*)');
$query->from($db->quoteName('#__my_table'));
$query->where($db->quoteName('name')." = :value");
$query->bind('value', $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).

use Joomla\CMS\Factory;
$db = Factory::getContainer()->get('DatabaseDriver');
$query = $db->getQuery(true);
$query->select('field_name');
$query->from($db->quoteName('#__my_table'));
$query->where($db->quoteName('some_name')." = :value");
$query->bind(':value', $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

See Also[edit]