Views: 1409 (Data available since 06.02.2017)

General architecture of API classes for working with databases:

  • The connection pool Bitrix\Main\DB\ConnectionPool contains information about connections of applications. There are default connections (main connections) and there may be a set of named connections to connect elsewhere, including to another database of a different type.
  • Specific connection classes inheriting the abstract class Bitrix\Main\DB\Connection ensure low-level operations with the database. They are divided into classes by databases.
  • Specific classes of forming SQL queries inheriting Bitrix\Main\DB\SqlHelper that help to form a query without going into the syntax of a specific database.
  • Specific classes for work with query execution result inheriting Bitrix\Main\DB\Result. They also vary according to databases.

These classes permit working with databases at a low level, but it is rarely required. Instead, working through ORM is recommended since ORM permits programming only at a business logic level.

Obtaining Database Connection, Named Connections

A connection may be obtained through applications and is, among other things, an entry point. From this entry point, instances of “star” objects for this application may be obtained that are needed for all (or almost all) pages or components of this application.

$connection = Main\Application::getConnection();
$sqlHelper = $connection->getSqlHelper();

$sql = "SELECT ID FROM b_user WHERE LOGIN = '".$sqlHelper->forSql($login, 50)."' ";

$recordset = $connection->query($sql);
while ($record = $recordset->fetch())
{
   ***

Various Forms of Query Execution Call

Accordingly, a call must be executed through the application in various forms: simple query, query with a limit for entries, scalar query, or a query “in general.”

$result1 = $connection->query($sql);
$result2 = $connection->query($sql, $limit);
$result3 = $connection->query($sql, $offset, $limit);

$cnt = $connection->queryScalar("SELECT COINT(ID) FROM table");

$connection->queryExecute("INSERT INTO table (NAME, SORT) VALES ('Name', 100)")

Obtaining Query Results:

$connection = Main\Application::getConnection();
$sqlHelper = $connection->getSqlHelper();

$sql = "SELECT ID FROM b_user WHERE LOGIN = '".$sqlHelper->forSql($login, 50)."' ";

$recordset = $connection->query($sql);
while ($record = $recordset->fetch())
{
   ***

Typed data are immediately returned as a type and not as lines or numbers.


Result Modification:

$connection = \Bitrix\Main\Application::getConnection();
$recordset = $connection->query("select * from b_iblock_element", 10);
$recordset->setFetchDataModifier(
   function ($data)
   {
       $data["NAME"] .= "!";
       return $data;
   }
);

while ($record = $recordset->fetch(\Bitrix\Main\Text\Converter::getHtmlConverter()))
   $data[] = $record

Result may be modified and conversed immediately, e.g. for preparation to XML displaying, etc.




Courses developed by «Bitrix», Inc.