Вход Регистрация
Файл: new_top/core/classes/Database.php
Строк: 73
<?php
/**
 * Simple PDO wrapper
 */

declare(strict_types=1);

class 
Database
{
    private static ?
PDO $pdo null;

    public static function 
init(PDO $pdo): void
    
{
        
self::$pdo $pdo;
    }

    public static function 
pdo(): PDO
    
{
        if (
self::$pdo === null) {
            throw new 
RuntimeException('Database not initialized');
        }
        return 
self::$pdo;
    }

    public static function 
query(string $sql, array $params = []): PDOStatement
    
{
        
$stmt self::pdo()->prepare($sql);
        
$stmt->execute($params);
        return 
$stmt;
    }

    public static function 
fetch(string $sql, array $params = []): ?array
    {
        
$row self::query($sql$params)->fetch();
        return 
$row === false null $row;
    }

    public static function 
fetchAll(string $sql, array $params = []): array
    {
        return 
self::query($sql$params)->fetchAll();
    }

    public static function 
fetchColumn(string $sql, array $params = [])
    {
        return 
self::query($sql$params)->fetchColumn();
    }

    public static function 
insert(string $table, array $data): int
    
{
        if (!
preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/'$table)) {
            throw new 
InvalidArgumentException('Invalid table name');
        }
        
$cols array_keys($data);
        foreach (
$cols as $col) {
            if (!
preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/'$col)) {
                throw new 
InvalidArgumentException('Invalid column name');
            }
        }
        
$placeholders array_map(function ($c) { return ':' $c; }, $cols);
        
$sql sprintf(
            
'INSERT INTO `%s` (`%s`) VALUES (%s)',
            
$table,
            
implode('`,`'$cols),
            
implode(','$placeholders)
        );
        
self::query($sql$data);
        return (int) 
self::pdo()->lastInsertId();
    }

    public static function 
update(string $table, array $datastring $where, array $whereParams = []): int
    
{
        if (!
preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/'$table)) {
            throw new 
InvalidArgumentException('Invalid table name');
        }
        
$set = [];
        foreach (
array_keys($data) as $col) {
            
$set[] = "`{$col}` = :{$col}";
        }
        
$sql sprintf('UPDATE `%s` SET %s WHERE %s'$tableimplode(', '$set), $where);
        
$stmt self::query($sqlarray_merge($data$whereParams));
        return 
$stmt->rowCount();
    }
}
Онлайн: 1
Реклама