# **Chapter 16: Data Log History and Recycle Bin — Undo for Your Database**
> **Prerequisites:** Chapter 15 (dbEngine, Page helpers)
> **Try it:** Tested code from gates `ex11dblog` and `ex12recycle`
> (`apps/examples/Ex11dblog.gate.php`, `Ex12recycle.gate.php`,
> shared helper `apps/examples/DbHistoryHelper.php`).
> Open `http://localhost/SartajPhpDoc/ex11dblog-install.html`, then
> `http://localhost/SartajPhpDoc/ex11dblog.html`.
---
## **16.1 Two Audit Tables, Two Jobs**
| Table | Records | Answers |
|-------|---------|---------|
| `data_log` | JSON snapshot **before** create/update | "What did this row look like yesterday? Undo that edit." |
| `recycle` | JSON snapshot of **deleted** rows | "Someone deleted it — bring it back." |
Both are plain tables you create in `db/` (this project: `db/db_audit.php`,
included from `db/db_index.php`). Both use the same column ideas:
```
userid, parentid, spcmpId, submit_timestamp, update_timestamp ← conventions
txttblname table the snapshot belongs to
numrecord_id primary key value of the row (data_log)
sqldata json_encode($row) snapshot
sql_group batch id — same value = restore together (0 = single)
restore_status 0 = open, 1 = already restored
```
`sql_group` is the clever bit: multi-row operations share one group
(`time()`), so **one restore undoes the whole batch**.
## **16.2 The Shared Helper (tested)**
`DbHistoryHelper` keeps the SQL in one place. Core functions:
```php
<?php
// apps/examples/DbHistoryHelper.php (excerpt — full source in apps/examples/)
/** Log a snapshot into data_log. $group: same time() for multi-row batches, 0 = single. */
public static function addLog($dbEngine, array $row, $tbl, $action, $recordId, $group = 0)
{
global $cmpId;
$req = SphpBase::sphpRequest();
$uid = $req->isSession('sid') ? $req->session('sid') : 0;
$pid = $req->isSession('parentid') ? $req->session('parentid') : 0;
$json = $dbEngine->cleanQuery(json_encode($row));
$t = time();
$sql = "INSERT INTO data_log (userid,parentid,txtaction,txttblname,numrecord_id,"
. "sqldata,sql_group,restore_status,submit_timestamp,update_timestamp,spcmpId) "
. "VALUES('$uid','$pid','$action','$tbl','$recordId','$json','$group','0','$t','$t','$cmpId')";
$dbEngine->executeQuery($sql);
}
/** Fetch one row by primary key (snapshot BEFORE the write). */
public static function fetchRow($dbEngine, $tbl, $id, $pk = 'id')
{
$result = $dbEngine->executeQueryQuick(
"SELECT * FROM $tbl WHERE $pk='" . $dbEngine->cleanQuery($id) . "'"
);
if ($dbEngine->isRows($result)) {
return $dbEngine->rowFetchAssoc($result);
}
return null;
}
/** Restore data_log entry (or whole sql_group) by writing the snapshot back. */
public static function restoreLog($dbEngine, $logId, $pk = 'id') { /* UPDATE from JSON */ }
/** Copy a row snapshot into recycle (before the hard delete). */
public static function addToRecycle($dbEngine, array $row, $tbl, $group = 0) { /* INSERT */ }
/** Re-INSERT deleted row(s) from recycle (or whole group). */
public static function restoreRecycle($dbEngine, $recycleId, $pk = 'id') { /* INSERT from JSON */ }
```
The rule that makes undo correct: **log the BEFORE image, then write.**
Update logs store the previous row; restore re-applies it.
## **16.3 Logging Creates and Updates (Ex11dblog)**
Insert — log the row as it exists right after `insertData`:
```php
<?php
// apps/examples/Ex11dblog.gate.php (tested)
$id = $this->page->insertData($form2, $extra);
if (!getCheckErr() && $id) {
$this->dbEngine->connect();
$row = DbHistoryHelper::fetchRow($this->dbEngine, 'ex11_item', $id);
if ($row) {
DbHistoryHelper::addLog($this->dbEngine, $row, 'ex11_item', 'create', $id, 0);
}
$this->dbEngine->disconnect();
$this->statusMsg = 'Created id=' . $id . ' (logged)';
}
```
Update — snapshot BEFORE `updateData`, under one group:
```php
<?php
$id = $form2->getRecID();
$this->dbEngine->connect();
$before = DbHistoryHelper::fetchRow($this->dbEngine, 'ex11_item', $id);
$group = time(); // batch id shared by all rows in this op
if ($before) {
DbHistoryHelper::addLog($this->dbEngine, $before, 'ex11_item', 'update', $id, $group);
}
$extra = array();
$extra[]['update_timestamp'] = time();
$this->page->updateData($form2, $extra);
$this->dbEngine->disconnect();
// statusMsg: 'Updated id=N (previous snapshot in data_log group=G)'
```
Multi-row batch (`ex11dblog-multitouch.html`, tested): touch the two newest
rows under **one** `sql_group` — restoring any one entry restores both:
```php
<?php
$this->dbEngine->connect();
$group = time();
$res = $this->dbEngine->executeQueryQuick('SELECT * FROM ex11_item ORDER BY id DESC LIMIT 2');
while ($row = $this->dbEngine->rowFetchAssoc($res)) {
DbHistoryHelper::addLog($this->dbEngine, $row, 'ex11_item', 'update', $row['id'], $group);
$newStatus = ($row['sltstatus'] == 1) ? 0 : 1;
$this->dbEngine->executeQuery(
"UPDATE ex11_item SET sltstatus='$newStatus', update_timestamp='" . time() . "' WHERE id='" . $row['id'] . "'"
);
}
$this->dbEngine->disconnect();
```
Restore (`ex11dblog-restorelog-LOGID.html`):
```php
<?php
$this->dbEngine->connect();
if (DbHistoryHelper::restoreLog($this->dbEngine, $evtp)) {
$this->statusMsg = 'Restored from data_log id=' . $evtp;
}
$this->dbEngine->disconnect();
```
`restoreLog` refuses entries with `restore_status='1'` (already restored) and,
when `sql_group > 0`, replays every open log in the group, then marks the
whole group restored.
## **16.4 Recycle Bin: Soft-Delete by Copy, Then Hard Delete (Ex12recycle)**
The framework's `deleteRec` is a hard delete. The production pattern
(tested in `Ex12recycle`) copies the row into `recycle` first:
```php
<?php
// apps/examples/Ex12recycle.gate.php (tested)
$this->dbEngine->connect();
$row = DbHistoryHelper::fetchRow($this->dbEngine, 'ex11_item', $evtp);
if ($row) {
DbHistoryHelper::addToRecycle($this->dbEngine, $row, 'ex11_item', 0);
$this->page->deleteRec($evtp); // NOW the hard delete
$this->statusMsg = 'Moved id=' . $evtp . ' to recycle';
} else {
setErr('ex12', 'Row not found');
}
$this->dbEngine->disconnect();
```
Multi-delete shares a group (`ex12recycle-multidelete.html`): snapshot all
rows with `$group = time()`, then delete each — one restore click brings the
batch back (`restoreRecycle` re-INSERTs every open entry in the group).
The bin screen is just a Pagination over `recycle` (same component pattern as
Chapter 15) with a Restore link per entry — see
`apps/examples/fronts/ex12recycle_bin.front`.
## **16.5 Design Notes**
1. **Snapshot = `json_encode($row)`** of the full assoc row — schema changes
later don't break old logs; restore writes back only columns that exist.
2. **`cleanQuery` the JSON** before embedding it in SQL (quotes inside JSON).
3. **Log outside the Page helper, around it** — the helpers know nothing about
`data_log`; your Gate adds the audit layer. (Chapter 12 showed why: helpers
only speak the dbEngine contract.)
4. **`restore_status` is one-way** — a restored log stays restored; audit
history is append-only.
5. **Permissions still apply** — expose restore/bin events only to roles that
may undo (Chapter 14 event-level bans fit perfectly).
6. If your primary key is not `id`, pass it: `fetchRow($db, $tbl, $id, 'item_uid')`
and `restoreLog($db, $logId, 'item_uid')`.
## **16.6 Verify It Yourself**
Against `http://localhost/SartajPhpDoc/`:
1. `ex11dblog-install.html` → schema (`ex11_item`, `data_log`, `recycle`)
2. `ex11dblog-addnew.html` → create an item → "Created id=N (logged)"
3. `ex11dblog-view-N.html` → edit → "Updated id=N (previous snapshot in data_log group=G)"
4. `ex11dblog-logs.html` → see create + update rows → **Restore** the update →
old values return
5. `ex11dblog-multitouch.html` → two rows logged under one group → restore one
entry → both rows revert
6. `ex12recycle.html` → **Del** a row → "Moved id=N to recycle"
7. `ex12recycle-bin.html` → **Restore** → row is back in the list
---
**Previous:** [Chapter 15 — Database Communication in the Gate](chapter15.md) ·
**Next:** [Chapter 17 — Built-in Form and Data Components](chapter17.md)