- includes/db.php: shared mysqli connection + parameterized query helpers (pqs_db/pqs_exec/pqs_rows/pqs_row/pqs_val), targets PHP 7.4+. - Replace 11 mysql_error() calls (undefined function on PHP 7+) with mysqli_error($link) / mysqli_connect_error() across getFSgame, getFSplayers, config, callsign, console. Only affected already-failed error paths. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
72 lines
2.2 KiB
PHP
72 lines
2.2 KiB
PHP
<?php
|
|
/**
|
|
* Centralized database access for PQS.
|
|
*
|
|
* Credentials live here intentionally: PQS runs on an air-gapped LAN where the
|
|
* localhost pqs/pqs account is a formality (see docs/ARCHITECTURE.md §1, §7).
|
|
*
|
|
* Targets PHP 7.4+ with mysqlnd (local test stack: PHP 8.3 / MariaDB; see
|
|
* dev/README.md). All new code should go through these helpers so queries are
|
|
* parameterized and the connection is opened once per request.
|
|
*/
|
|
|
|
const PQS_DB_HOST = 'localhost';
|
|
const PQS_DB_USER = 'pqs';
|
|
const PQS_DB_PASS = 'pqs';
|
|
const PQS_DB_NAME = 'pqs';
|
|
|
|
/**
|
|
* Shared mysqli connection, opened once per request.
|
|
* mysqli is put into exception-reporting mode (the default since PHP 8.1) so
|
|
* failures raise mysqli_sql_exception instead of silently returning false.
|
|
*/
|
|
function pqs_db(): mysqli
|
|
{
|
|
static $link = null;
|
|
if ($link === null) {
|
|
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
|
|
$link = new mysqli(PQS_DB_HOST, PQS_DB_USER, PQS_DB_PASS, PQS_DB_NAME);
|
|
}
|
|
return $link;
|
|
}
|
|
|
|
/**
|
|
* Prepare, bind and execute a parameterized statement; return the statement.
|
|
* $types is a mysqli bind_param type string, e.g. "si" for (string, int).
|
|
*/
|
|
function pqs_exec(string $sql, string $types = '', array $params = []): mysqli_stmt
|
|
{
|
|
$stmt = pqs_db()->prepare($sql);
|
|
if ($types !== '') {
|
|
$stmt->bind_param($types, ...$params);
|
|
}
|
|
$stmt->execute();
|
|
return $stmt;
|
|
}
|
|
|
|
/** Run a query and return all rows as associative arrays. */
|
|
function pqs_rows(string $sql, string $types = '', array $params = []): array
|
|
{
|
|
$stmt = pqs_exec($sql, $types, $params);
|
|
$res = $stmt->get_result();
|
|
$rows = $res ? $res->fetch_all(MYSQLI_ASSOC) : [];
|
|
$stmt->close();
|
|
return $rows;
|
|
}
|
|
|
|
/** Run a query and return the first row (assoc) or null. */
|
|
function pqs_row(string $sql, string $types = '', array $params = []): ?array
|
|
{
|
|
return pqs_rows($sql, $types, $params)[0] ?? null;
|
|
}
|
|
|
|
/** Run a query and return a single scalar (first column of first row) or null. */
|
|
function pqs_val(string $sql, string $types = '', array $params = [])
|
|
{
|
|
$stmt = pqs_exec($sql, $types, $params);
|
|
$res = $stmt->get_result();
|
|
$val = ($res && ($r = $res->fetch_row())) ? $r[0] : null;
|
|
$stmt->close();
|
|
return $val;
|
|
}
|