# **Chapter 15: Database Communication in the Gate — dbEngine, db_index, and Pagination**
> **Prerequisites:** Chapters 4-7 (Page Events, HTMLForm, Pagination), Chapter 12 (dbEngine contract)
> **Try it:** Tested code from gate `ex10db`
> (`apps/examples/Ex10db.gate.php` + `apps/examples/fronts/ex10db_*.front`).
> Open `http://localhost/SartajPhpDoc/ex10db-install.html` once, then
> `http://localhost/SartajPhpDoc/ex10db.html`.
---
## **15.1 The Gate's Database Toolkit**
Every Gate already holds a database handle: `$this->dbEngine` (the engine
instance behind `SphpBase::dbEngine()` — see Chapter 12 for the contract).
A Gate talks to the database at three levels:
| Level | API | You write |
|-------|-----|-----------|
| Raw SQL | `$this->dbEngine->executeQuery($sql)` | SQL strings |
| Page helpers | `$this->page->insertData($form2, $extra)` | Form + `$extra` only |
| Components | `dfield`/`dtable` + `Pagination` | Front markup only |
Pick the highest level that does the job; drop a level only when the higher
one cannot express what you need.
## **15.2 The Standard CRUD Gate (tested)**
`Ex10db` is the canonical shape — the same skeleton as the `task` gate in
Chapter 11:
```php
<?php
// apps/examples/Ex10db.gate.php (tested)
use Sphp\Gates\BasicGate;
use Sphp\Tools\FrontFile;
class Ex10db extends BasicGate
{
public $genFormFront = null; // edit form
public $showallFront = null; // list
public $pageName = 'Ex10 Notes';
public $formButton = 'Save';
public $statusMsg = '';
public function onstart()
{
global $masterf;
$this->getAuthenticate('GUEST,MEMBER,ADMIN');
// Default table for Page::insertData / updateData / viewData / deleteRec
$this->setTableName('ex10_note');
$this->genFormFront = new FrontFile('edit');
$this->showallFront = new FrontFile('list');
$this->setMasterFile($masterf);
$showall = $this->showallFront->getComponent('showall');
if ($showall !== null) {
$showall->fu_setPerPageRows(10);
$showall->fu_setWhere(' ORDER BY id DESC ');
}
}
}
```
`setTableName()` is what makes the Page helpers work without repeating the
table everywhere: `deleteRec($id)` becomes `DELETE FROM ex10_note WHERE
id='$id'`, and `viewData`/`insertData` fall back to it when a component has no
`dtable`.
## **15.3 Schema Installation: the db_index Pattern**
Production projects keep SQL design under `db/` with one entry point
(`db/db_index.php`) that includes module files. A Gate install event runs it
once (tested — same pattern as `mebhome` install):
```php
<?php
/** URL: ex10db-install.html */
public function page_event_install($evtp)
{
$db = $this->dbEngine;
$db->connect();
// Project SQL design lives under db/; entry point pulls modules.
include_once(SphpBase::sphpSettings()->getProjectPath() . '/db/db_index.php');
$db->disconnect();
$this->statusMsg = 'Installed: db/db_index.php';
$this->setFrontFile($this->showallFront);
}
```
Inside `db/db_index.php` each module file just runs CREATE statements through
the live engine (see `db/db_book2.php` from Chapter 4):
```php
<?php
// db/db_ex10.php style — plain SQL through the engine
$sql = "CREATE TABLE IF NOT EXISTS ex10_note ( ... )";
\SphpBase::dbEngine()->executeQuery($sql);
```
Why this pattern:
- One command installs the whole schema on any engine (SQLite/MySQL/PDO —
Chapter 12 swapped engines with zero Gate changes)
- `IF NOT EXISTS` makes install idempotent — safe to click twice
- Schema stays reviewable as plain SQL files in version control
## **15.4 Insert / Update / Delete via Page Helpers**
```php
<?php
public function page_submit()
{
$form2 = $this->genFormFront->getComponent('form2');
// isUpdateRequest() = true when the form carries a RecID (edit mode)
if ($form2->isUpdateRequest()) {
$this->doUpdate($form2);
} else {
$this->doInsert($form2);
}
}
private function doInsert($form2)
{
global $cmpId;
$extra = array();
$extra[]['userid'] = 0;
$extra[]['parentid'] = 0;
$extra[]['spcmpId'] = $cmpId;
$extra[]['submit_timestamp'] = time();
$extra[]['update_timestamp'] = time();
$id = $this->page->insertData($form2, $extra);
if (!getCheckErr() && $id) {
$this->statusMsg = 'Inserted id=' . $id;
$this->setFrontFile($this->showallFront);
} else {
setErr('ex10', 'Insert failed');
$this->setFrontFile($this->genFormFront);
}
}
private function doUpdate($form2)
{
$extra = array();
$extra[]['update_timestamp'] = time();
$this->page->updateData($form2, $extra); // WHERE id = $form2->getRecID()
if (!getCheckErr()) {
$this->statusMsg = 'Updated id=' . $form2->getRecID();
$this->setFrontFile($this->showallFront);
} else {
setErr('ex10', 'Update failed');
$this->setFrontFile($this->genFormFront);
}
}
/** URL: ex10db-delete-5.html */
public function page_event_delete($evtp)
{
if ($evtp !== '' && $evtp !== null) {
$this->page->deleteRec($evtp);
$this->statusMsg = 'Deleted id=' . $evtp;
}
$this->setFrontFile($this->showallFront);
}
```
The `$extra` columns (`userid`, `parentid`, `spcmpId`, `submit_timestamp`,
`update_timestamp`) are the framework table conventions — keep them and
history/recycle features (Chapter 16) plus multi-tenant filters keep working.
When a row belongs to a logged-in user, take the ids from the session instead
of hard-coding 0 (pattern from `Ex11dblog`, tested):
```php
$extra[]['userid'] = SphpBase::sphpRequest()->isSession('sid')
? SphpBase::sphpRequest()->session('sid') : 0;
$extra[]['parentid'] = SphpBase::sphpRequest()->isSession('parentid')
? SphpBase::sphpRequest()->session('parentid') : 0;
```
## **15.5 Raw SQL When You Need It**
For aggregates and reports, use the engine directly — always
`connect → query → fetch → disconnect` (tested):
```php
<?php
/** URL: ex10db-count.html — raw SQL helper demo */
public function page_event_count($evtp)
{
$db = $this->dbEngine;
$db->connect();
$result = $db->executeQueryQuick('SELECT COUNT(*) AS c FROM ex10_note');
$row = $db->rowFetchAssoc($result);
$db->disconnect();
$this->statusMsg = 'COUNT(*)=' . (isset($row['c']) ? $row['c'] : '?');
$this->setFrontFile($this->showallFront);
}
```
Engine call cheat-sheet (full contract in Chapter 12):
| Task | Call |
|------|------|
| Run SQL | `connect()` → `executeQuery($sql)` → `disconnect()` |
| One-shot (auto-connect) | `executeQueryQuick($sql)` |
| Fetch assoc row | `rowFetchAssoc($result)` in a `while` loop |
| Has rows? | `isRows($result)` |
| Exists? | `isRecordExist($sql)` |
| Escape a value | `cleanQuery($value)` |
| New id | `lastInsertId()` |
| Build INSERT/UPDATE | `insertSql($frm, $tbl)` / `updateSql($frm, $tbl, $where)` |
Escape anything that came from the browser before interpolating into SQL:
`"... WHERE txttitle='" . $db->cleanQuery($kw) . "'"`.
## **15.6 The List Side: Pagination Component + dtable**
The list Front needs no Gate query at all — `Pagination` reads `dtable` and
pages itself (Chapter 7 covers the markup; the DB view is repeated here):
```html
<tbody id="showall" runat="server" path="uikit/data/Pagination.php"
fun-setFieldNames="id,txttitle,sltstatus"
dtable="ex10_note"
fun-setPerPageRows="10">
<tr>
<td runas="holder" sphp-comp="showall" dfield="id"></td>
<td runas="holder" sphp-comp="showall" dfield="txttitle"></td>
<td>##{($showall->getRow('sltstatus') == 1) ? 'Active' : 'Off'}#</td>
<td>
<a href="##{getEventUrl('view', $showall->getRow('id'))}#">Edit</a>
|
<a href="##{getEventUrl('delete', $showall->getRow('id'))}#"
onclick="return confirm('Delete?');">Del</a>
</td>
</tr>
</tbody>
<div id="pagebar">##{$showall->getPageBar()}#</div>
```
- `fun-setFieldNames` = columns the component SELECTs
- `dtable` = table; `fu_setWhere()` in the Gate = ORDER/WHERE
- `$showall->getRow('col')` = current row value inside the template row
- Non-rendered columns are still available through `getRow()`
## **15.7 Edit Flow: viewData Fills the Form**
```php
<?php
/** URL: ex10db-view-5.html — fill dfield-bound children from table */
public function page_event_view($evtp)
{
if ($evtp === '' || $evtp === null) {
$this->page_new();
return;
}
$this->pageName = 'Edit Note';
$this->formButton = 'Update';
$form2 = $this->genFormFront->getComponent('form2');
$this->page->viewData($form2, $evtp); // SELECT * WHERE id=$evtp + setRecID
$this->setFrontFile($this->genFormFront);
}
```
`viewData` also calls `$form->setRecID($recID)` — that is what flips
`isUpdateRequest()` to true when the form posts back, so one `page_submit()`
handles both insert and update.
## **15.8 Verify It Yourself**
Against `http://localhost/SartajPhpDoc/`:
1. `ex10db-install.html` → "Installed: db/db_index.php"
2. `ex10db.html` → paginated list
3. `ex10db-addnew.html` → save → "Inserted id=N"
4. `ex10db-view-N.html` → form filled → save → "Updated id=N"
5. `ex10db-count.html` → "COUNT(*)=n"
6. `ex10db-delete-N.html` → "Deleted id=N"
---
**Previous:** [Chapter 14 — Permissions and Authentication](chapter14.md) ·
**Next:** [Chapter 16 — Data Log History and Recycle Bin](chapter16.md)