<?php
namespace myclass;

class Db {

    private static $host = "957lan.dnstoo.com";
    private static $user = "jyan_f";
    private static $password = "golang";

    private static $port = "3306";
    private static $dbname = "jyan";
    private static $instance = null;

    // 获取PDO实例（单例模式）
    private static function getConnection() {
        if (self::$instance == null) {
            $dsn = "mysql:host=".self::$host.";port=".self::$port.";dbname=".self::$dbname.";charset=utf8mb4";
            self::$instance = new \pdo($dsn, self::$user, self::$password);
            self::$instance->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
            self::$instance->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
        }
        return self::$instance;
    }

    // 查询单行数据
    public static function Row($sql, array $arr = []): ?array {
        $stmt = self::getConnection()->prepare($sql);
        $stmt->execute($arr);
        return $stmt->fetch(\PDO::FETCH_ASSOC) ?: null;
    }

    // 查询多行数据
    public static function Rows($sql, array $arr = []): ?array {
        $stmt = self::getConnection()->prepare($sql);
        $stmt->execute($arr);
        $result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        return $result ?: null;
    }

    // 执行SQL语句（INSERT/UPDATE/DELETE）
    public static function Exec($sql, array $arr = []): int {
        $stmt = self::getConnection()->prepare($sql);
        $stmt->execute($arr);
        return $stmt->rowCount();
    }

    // 自动拼接INSERT语句并执行
    public static function AutoInsert(string $table, array $arr): int {
        if (empty($arr)) return 0;
        
        $keys = implode(',', array_keys($arr));
        $placeholders = implode(',', array_fill(0, count($arr), '?'));
        $sql = "INSERT INTO $table ($keys) VALUES ($placeholders)";
        
        $stmt = self::getConnection()->prepare($sql);
        $stmt->execute(array_values($arr));
        return $stmt->rowCount();
    }

    // 执行INSERT并返回最后插入ID
    public static function lastInsertId(string $sql, array $arr = []): int {
        $stmt = self::getConnection()->prepare($sql);
        $stmt->execute($arr);
        return (int)self::getConnection()->lastInsertId();
    }

    // 清空表数据（更高效的实现）
    public static function deleteAll(string $table): bool {
        if (empty($table)) return false;
        
        // 防止SQL注入，验证表名是否合法
        if (!preg_match('/^[a-zA-Z0-9_]+$/', $table)) {
            return false;
        }
        
        $stmt = self::getConnection()->prepare("DELETE FROM $table");
        return $stmt->execute();
    }

}