<?php
function db() {
    static $pdo = null;
    if ($pdo instanceof PDO) return $pdo;
    try {
        $dsn = 'mysql:host='.DB_HOST.';port='.DB_PORT.';dbname='.DB_NAME.';charset=utf8mb4';
        $pdo = new PDO($dsn, DB_USER, DB_PASS, array(
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false
        ));
        return $pdo;
    } catch (Throwable $e) { return null; }
}
function db_all($sql, $params=array()) { $p=db(); if(!$p) return array(); $s=$p->prepare($sql); $s->execute($params); return $s->fetchAll(); }
function db_one($sql, $params=array()) { $rows=db_all($sql,$params); return $rows ? $rows[0] : null; }
function db_exec($sql, $params=array()) { $p=db(); if(!$p) return false; $s=$p->prepare($sql); return $s->execute($params); }
