MagratheaPHP2
Up to date Narrative last written —; no source changes since. Method signatures below are reflected live.

Database — MySQLi Connection Wrapper

File: src/DB/Database.php Namespace: Magrathea2\DB Extends: Singleton

The primary database access layer. Wraps a mysqli connection and provides query execution methods, transaction support, prepared statements, and file import.


Constants (Fetch Modes)

ConstantValueDescription
FETCH_ASSOC1Returns rows as associative arrays, keys lowercased (default)
FETCH_OBJECT2Returns rows as stdClass objects (keys as MySQL returns them)
FETCH_NUM3Returns rows as numeric arrays (not settable with SetFetchMode())
FETCH_ARRAY4Returns rows as both assoc + numeric (not settable with SetFetchMode())

Rows come back as associative arrays unless SetFetchMode("object") was called. Model loading (LoadObjectFromTableRow()) accepts both, so switching modes doesn't break the ORM, but every raw QueryAll()/QueryRow() caller in the request then gets objects: switch only if the whole app expects them.


Properties

PropertyTypeDescription
$mysqlimysqliThis instance's connection (null until the first query)
$connDetailsarrayConnection parameters
$fetchmodeintCurrent fetch mode (null until SetFetchMode(), which reads as FETCH_ASSOC)
$countintNumber of rows returned by the last SELECT
$affectedRowsintRows affected by the last query (see LastAffectedRows())

Connection lifecycle

Since 2.4.0, each Database instance opens one connection, on its first query, and reuses it for the rest of the request. It's closed automatically at the end of the request (a shutdown function closes every open instance). Before 2.4.0, every query opened and closed its own connection.

So session state lasts the whole request: SET @var, GET_LOCK(), temporary tables and LAST_INSERT_ID() survive between calls.

```php class ReportsDb extends \Magrathea2\DB\Database {}

ReportsDb::Instance()->SetConnection("reports.host", "reports", "user", "pass"); $rows = ReportsDb::Instance()->QueryAll("SELECT * FROM daily_totals"); ```

Models, Controls and the query builder always use Database::Instance(); only your own calls go to the subclass.

Timezone sync

Since 2.4.0, when the config has a timezone, every new connection runs SET time_zone = '<PHP's timezone>' right after set_charset(). MySQL's NOW(), CURRENT_TIMESTAMP, column defaults, ON UPDATE CURRENT_TIMESTAMP and triggers fired by this connection then use the same zone as PHP's now().

TimezoneCheck::Run() (shown on the admin's Server page and the Bootstrap wizard's config step) reports the sync state and whether the offset fallback was used.

Query errors

Since 2.4.0, every query method (Query*(), PrepareAndExecute(), QueryTransaction(), Transaction()'s begin/commit) throws MagratheaDBException on a MySQL error, whatever mysqli's error reporting mode:

Before 2.4.0, with PHP 8.1+'s default reporting, most methods let mysqli's mysqli_sql_exception out as is: code that catches mysqli_sql_exception around framework calls must catch MagratheaDBException now. The exceptions are QueryTransaction() and Query() with mysqli reporting off: they still return false.

In an API, a MagratheaDBException (or a mysqli_sql_exception) is always answered with HTTP 500: its code is an errno, not a status (4031 would otherwise map to 403).

use Magrathea2\Exceptions\MagratheaDBException;
use Magrathea2\Exceptions\MagratheaApiException;

try {
    $user->Insert();
} catch (MagratheaDBException $ex) {
    if ($ex->getCode() !== 1062) throw $ex;
    throw new MagratheaApiException("Email already registered", 409);
}

Lost connections

When MySQL reports error 2006 ("server has gone away"), 2013 ("lost connection during query") or 4031 (MySQL 8.0.24+: "disconnected by the server because of inactivity", sent to a client idle past wait_timeout), the query methods throw MagratheaDBConnectionLostException (a MagratheaDBException, so existing catch(MagratheaDBException) blocks still catch it). Before throwing, the dead connection is dropped, so the next call on the same instance opens a new one.

The framework never retries. Whether a statement is safe to run twice depends on the statement, and only the app knows that:

CodeMeaningSafe to retry?
2006Server has gone away: the statement was probably not executedUsually
2013Lost connection during query: the statement may have executedOnly if it's idempotent
4031Disconnected for inactivity: the statement was not executedYes

A reconnect is also a new MySQL session: locks, @vars and temporary tables from before are gone.

use Magrathea2\DB\Database;
use Magrathea2\Exceptions\MagratheaDBConnectionLostException;

while (true) {
    Database::Instance()->Disconnect(); // fresh connection for every job
    $job = NextJob();
    try {
        ProcessJob($job);
    } catch (MagratheaDBConnectionLostException $ex) {
        // $ex->getCode() is 2006, 2013 or 4031; retry only if ProcessJob() is idempotent
        Requeue($job);
    }
}

Connection Methods

SetConnection(string $host, string $database, string $username, string $password, int|string|null $port = null): Database

Set connection parameters. Called internally by MagratheaPHP::Connect(), which reads db_host, db_name, db_user, db_pass and db_port from the active environment's config section. An empty $port (or no db_port in the config) uses mysqli's default port (php.ini mysqli.default_port, normally 3306). With localhost as host, mysqli connects through the Unix socket and ignores the port.

Database::Instance()->SetConnection("localhost", "mydb", "root", "pass", 3306);

SetConnectionArray(array $dsn_arr): Database

Set connection from an array with keys hostspec, database, username, password and, optionally, port.

Database::Instance()->SetConnectionArray([
    "hostspec" => "localhost",
    "database" => "mydb",
    "username" => "root",
    "password" => "secret",
]);

OpenConnectionPlease(): bool

Opens this instance's connection if it isn't open yet (it reuses it otherwise). Every query method calls it, so you don't need to. Throws MagratheaDBException on failure; a failed connection isn't kept, so the next call tries again.

CloseConnectionThanks(): void

Does nothing since 2.4.0; kept for compatibility. The connection stays open until the end of the request. Use Disconnect() to close it.

Disconnect(): void

Closes this instance's connection now. The next query opens a new one. Use it at the start of each job in long-running workers, or before pcntl_fork() (a child must never share its parent's connection).

Database::DisconnectAll(): void (static)

Closes the connection of every Database instance (including subclasses). Runs automatically at the end of the request.

LastAffectedRows(): int

Rows affected by the last Query*() or PrepareAndExecute() call (for a SELECT, the number of rows returned). PrepareAndExecute()'s return value (the insert id, or true) doesn't change.

SetTimezoneSync(bool $sync): Database

Sets whether new connections run SET time_zone with PHP's timezone (see "Timezone sync" above). MagratheaPHP::Connect() calls it with TimezoneCheck::SyncState() === TimezoneCheck::SYNC_ON. Off by default on a Database set up without Connect().

GetSyncedTimezone(): ?array

What the current connection's time_zone was set to: ["zone" => "America/Sao_Paulo", "fallback" => false], or ["zone" => "-03:00", "fallback" => true] when MySQL didn't know the name. null when there's no connection or the sync is off. DatabaseSimulate always returns null.

CreateConnection(): \mysqli (protected)

Creates the actual mysqli connection; OpenConnectionPlease() calls it. Override it in a subclass to hand back a different connection object, e.g. a fake one in tests (the framework's own tests do this, see src/Tests/MagratheaTests/databaseConnectionTest.php).

getDatabaseName(): string|null

Returns the name of the currently connected database.

SetFetchMode(string $fetch): Database

Changes the fetch mode for this instance's next queries. Accepts "object" and "assoc"; any other value (including "num" and "array") sets "assoc".

Database::Instance()->SetFetchMode("object"); // rows as stdClass from now on

Query Methods

Query(string $sql): object

Executes a raw SQL query. Returns a mysqli_result or throws MagratheaDBException.

$result = Database::Instance()->Query("SELECT * FROM users WHERE active = 1");

QueryAll(string $sql): array

Executes a SELECT and returns all rows as an array (format depends on fetch mode).

$users = Database::Instance()->QueryAll("SELECT * FROM users");
foreach ($users as $user) {
    echo $user["name"]; // FETCH_ASSOC (default); $user->name after SetFetchMode("object")
}

QueryRow(string $sql): array|object

Executes a SELECT and returns only the first row. With no rows it returns an empty array, in every fetch mode.

$user = Database::Instance()->QueryRow("SELECT * FROM users WHERE id = 1");
if (empty($user)) throw new MagratheaApiException("User not found", 404);
echo $user["email"];

QueryOne(string $sql): mixed

Executes a SELECT and returns only the first column of the first row (scalar value).

$count = Database::Instance()->QueryOne("SELECT COUNT(*) FROM users");
echo $count; // "42"

QueryTransaction(array $query_array): bool

Executes an array of SQL statements as a single transaction. It stops at the first failing statement (the rest aren't sent), rolls everything back and turns autocommit back on. How the failure reaches you depends on mysqli's error reporting, as with every other query method:

It returns true once the commit succeeds. A failed COMMIT is handled like a failed statement. A lost connection, on a statement or on the COMMIT, throws MagratheaDBConnectionLostException without a rollback attempt (MySQL discards the transaction with the connection). If the rollback itself fails, the connection is dropped, and the error you get is still the original one.

try {
    Database::Instance()->QueryTransaction([
        "INSERT INTO orders (user_id, total) VALUES (1, 99.99)",
        "UPDATE inventory SET stock = stock - 1 WHERE product_id = 5",
    ]);
} catch (MagratheaDBException $e) {
    // nothing was written
}

It only takes fixed SQL strings. DDL (CREATE, ALTER, TRUNCATE) commits implicitly in MySQL, so a DDL statement in the list ends the transaction early.

QueryMulti(array|string $queries, bool $killable = true): array

Executes multiple SQL statements, in order, on the same connection. If $queries is a string, it's split on ; followed by a newline. Returns one entry per statement: ["query" => …, "success" => bool, "result" => …], where result holds the rows (as assoc arrays) for a SELECT, ["success" => true] for a CREATE, an empty array for other statements, or the error message when success is false. (Before 2.4.0, result was always empty for SELECTs.) Query() calls it when its SQL holds more than one statement.

With $killable = true (the default), the first failing statement throws MagratheaDBException and the rest aren't sent. With false, a failing statement is recorded (success => false, the error message in result) and the next statements still run, whatever the reporting mode (before 2.4.0, it only worked with reporting off). A lost connection (MagratheaDBConnectionLostException) always throws, even with false: the next statements can't run without it.

$results = Database::Instance()->QueryMulti([
    "SELECT * FROM users",
    "SELECT * FROM products",
]);

ImportFile(string $file_path, bool $killable = true): array

Reads a .sql file and executes all statements within it.

Database::Instance()->ImportFile("/migrations/001_create_users.sql");

Prepared Statements

PrepareAndExecute(string $query, array $arrTypes, array $arrValues): mixed

Executes a prepared statement, for writes (INSERT, UPDATE, DELETE) with untrusted values. It returns the insert id, or true when there's none; it never returns rows, so don't use it for a SELECT (use the query builder's array forms, or Escape(), for reads with untrusted input). It's what the model's Insert(), Update() and Delete() run.

$id = Database::Instance()->PrepareAndExecute(
    "INSERT INTO users (email, active) VALUES (?, ?)",
    ["string", "boolean"],
    ["user@example.com", true]
);

$arrTypes holds Magrathea field types, one per value, not mysqli letters: "int", "integer" and "boolean" are bound as integers, "float" as a double, and anything else ("string", "text", "datetime", "decimal", …) as a string. A mysqli letter like "i" isn't recognized, so it's bound as a string too.

The model's Insert()/Update()/Delete() pass GetDataTypeFromField()'s categories: int/boolean fields (and an int PK) are bound as integers, and float fields as strings ("decimal"), so exact values don't go through a PHP float. decimal fields (2.4.0) are bound as strings too ("text"). Before 2.4.0 every model value was bound as a string (MySQL converted them).

A failed prepare or execute throws MagratheaDBException (code = MySQL errno), with the query and values in its query and values properties; a lost connection throws MagratheaDBConnectionLostException (see Query errors). Before 2.4.0, with mysqli error reporting off, a failed execute printed got error! and returned null, so a failed Insert() set the object's PK to null and carried on.


Escaping

Escape(mixed $value): string

Escapes a value for safe interpolation into a raw SQL string (wraps mysqli::real_escape_string, opening a connection if needed). This is what the query builder uses internally for Query::Where(array)/WhereArray()/W(), QueryUpdate::Set()/SetArray(), and QueryInsert::Values() — you only need to call it yourself when building a raw SQL fragment by hand.

$safe = Database::Instance()->Escape($_GET["search"]);
$sql = "SELECT * FROM products WHERE name LIKE '%$safe%'";
Still prefer PrepareAndExecute over hand-built strings when possible.

Transactions

Transaction(callable $fn): mixed

Runs $fn inside a transaction and returns what $fn returns. Everything $fn does on the connection (raw queries, model Save()/Insert()/Update()/Delete(), GetWhere(), the query builder, QueryRow("SELECT … FOR UPDATE")) is committed together when $fn returns, or rolled back if it throws.

use Magrathea2\DB\Database;

$orderId = Database::Instance()->Transaction(function() use ($cart) {
    $stock = Database::Instance()->QueryOne("SELECT stock FROM products WHERE id = 5 FOR UPDATE");
    if ($stock < 1) throw new MagratheaApiException("Out of stock", 409);

    $order = new Order();
    $order->user_id = $cart->user_id;
    $order->Insert();
    Database::Instance()->Query("UPDATE products SET stock = stock - 1 WHERE id = 5");
    return $order->id;
});

Things to know:


Testing / Mock

Mock(): void

Replaces the internal MySQLi connection with a mock that does nothing. Useful for unit tests. The mock's Transaction() follows the same nesting and failure rules, and logs START TRANSACTION, COMMIT and ROLLBACK as simulated queries in the Debugger.

Database::Instance()->Mock();

Full Usage Examples

Basic SELECT

use Magrathea2\DB\Database;

$db = Database::Instance();
$rows = $db->QueryAll("SELECT id, name, email FROM users WHERE active = 1");

foreach ($rows as $row) {
    printf("[%d] %s <%s>\n", $row["id"], $row["name"], $row["email"]);
}

Counting rows

$total = Database::Instance()->QueryOne("SELECT COUNT(*) FROM orders WHERE status = 'pending'");
echo "Pending orders: $total";

Transaction (multi-step insert)

Database::Instance()->QueryTransaction([
    "INSERT INTO invoices (user_id, amount) VALUES (10, 250.00)",
    "INSERT INTO invoice_items (invoice_id, product_id) VALUES (LAST_INSERT_ID(), 3)",
    "UPDATE products SET stock = stock - 1 WHERE id = 3",
]);

Safe input with prepared statement

$email = $_POST["email"]; // untrusted user input

Database::Instance()->PrepareAndExecute(
    "UPDATE users SET email = ? WHERE id = ?",
    ["string", "int"],
    [$email, $userId]
);
$changed = Database::Instance()->LastAffectedRows();

Notes

Class Reference — Database

Magrathea2\DB\Database extends Singleton implements Stringable /home/platypusweb/platypusweb.com.br/site/magratheaphp2/src/DB/Database.php

This class will provide a layer for connecting with mysql

CloseConnectionThanks()

Already used you.. Bye.

ImportFile($file_path, $killable = true)

imports a .sql file to the database

ParamTypeDefault
$file_path mixed required
$killable mixed true
Mock(): void
OpenConnectionPlease(): bool

Open connection, please. Please! 0=)

PrepareAndExecute($query, $arrTypes, $arrValues)

Prepares and execute a query and returns the inserted id (if any) @todo validates types and avoids injection. Does it?

ParamTypeDefault
$query mixed required
$arrTypes mixed required
$arrValues mixed required
Query(string $sql)

executes the query and returns the full data

ParamTypeDefault
$sql string required
QueryAll(string $sql)

executes the query and returns the full data in an array

ParamTypeDefault
$sql string required
QueryMulti($queries, $killable = true)

receives a string with multiple queries and executes them all

ParamTypeDefault
$queries mixed required
$killable mixed true
QueryOne($sql)

executes the query and returns only the first value of the first row of the result

ParamTypeDefault
$sql mixed required
QueryRow(string $sql): object|array

executes the query and returns only the first row of the result

ParamTypeDefault
$sql string required
QueryTransaction($query_array)

receives an array of queries and executes them all

ParamTypeDefault
$query_array mixed required
SetConnection($host, $database, $username, $password, $port = null): Magrathea2\DB\Database

Setups connection

ParamTypeDefault
$host mixed required
$database mixed required
$username mixed required
$password mixed required
$port mixed null
SetConnectionArray($dsn_arr): Magrathea2\DB\Database

Sets the connection array object array( 'hostspec' => $host, 'database' => $database, 'username' => $username, 'password' => $password, );

ParamTypeDefault
$dsn_arr mixed required
SetFetchMode($fetch): Magrathea2\DB\Database

Sets fetchmode, according with MDB2 values. Default mode: assoc. options available: assoc: array with keys as the column names object: object with columns as properties if anything different from those values is sent, "assoc" is used

ParamTypeDefault
$fetch mixed required
getDatabaseName(): ?string

Gets database name