mirror of
https://github.com/avecms/AVE.cms.git
synced 2026-08-01 00:45:44 +00:00
3.0 KiB
3.0 KiB
Working with the database
The engine works with MySQL/MariaDB through the thin façade DB (a wrapper over mysqli).
The class is App\Common\Db\DB, but the short global alias DB is used everywhere.
The query result is returned as object DB_Result.
$doc = DB::query('SELECT * FROM ' . $t . ' WHERE Id = %i', 42)->getAssoc();
Section map
| Page | What about |
|---|---|
| Table names (resolvers) | How to correctly get the table name (ContentTables, SystemTables, ...) instead of the hardcode. |
| Placeholders | Full analysis of %i %s %ss %li %hc … with examples of each. |
| Queries | DB::query() and variants (queryAssoc, queryOneColumn ...), debugging. |
| Read result (DB_Result) | getAll / getAssoc / getValue / getOne …, semantics and pitfalls. |
| CRUD helpers | Insert / Update / Delete / Replace / insertUpdate, insertId, affectedRows. |
| Transactions | startTransaction / commit / rollback. |
| Query cache | setTtl / setCache / setTags / clearTags. |
| Safety and Shielding | Injection protection, escape / quote / safe. |
Connection
The connection is raised once at system/bootstrap.php (DB::getInstance($config)),
therefore, there is no need to initialize anything in controllers/models - right away
DB::query(...).
DB::connection('default'); // именованное соединение
DB::setPrefix('marketplace'); // префикс (обычно из настроек)
DB::mysqli(); // «сырой» mysqli при необходимости
DB::version(); // версия сервера
DB::getDatabase(); // имя текущей БД
Quick start
use App\Content\ContentTables;
$t = ContentTables::table('documents'); // for example, 'ave_documents'
// список (массив ассоц. строк; на пустой выборке — false)
$items = DB::query('SELECT * FROM ' . $t . ' WHERE rubric_id = %i ORDER BY Id DESC', 5)->getAll() ?: array();
// одна строка
$doc = DB::query('SELECT * FROM ' . $t . ' WHERE Id = %i', 42)->getAssoc();
// один скаляр
$count = (int) DB::query('SELECT COUNT(*) FROM ' . $t)->getValue();
// вставка
DB::Insert($t, array('document_title' => 'Тест', 'rubric_id' => 5));
$id = (int) DB::insertId();
// обновление / удаление
DB::Update($t, array('document_title' => 'Новый'), 'Id = %i', $id);
DB::Delete($t, 'Id = %i', $id);
Three rules
- Table name - via resolver (
ContentTables::table('documents')), not a string. → tables.md - Values - only through placeholders (
%i,%s, ...), never merge user input in SQL. → placeholders.md, security.md getAll()on an empty sample returnsfalse, and not[]- write?: array(). → results.md