74 lines
2.6 KiB
PHP
74 lines
2.6 KiB
PHP
<?php
|
|
namespace App\Library;
|
|
|
|
use App\Library\DatabaseConfig;
|
|
use App\Library\Logger;
|
|
use PDOException;
|
|
use PDO;
|
|
class Database
|
|
{
|
|
private PDO $pdo;
|
|
private static $logFile = 'database.log';
|
|
public function __construct(DatabaseConfig $config)
|
|
{
|
|
try {
|
|
$dsn = $config->getDsn();
|
|
$username = $config->getUsername();
|
|
$password = $config->getPassword();
|
|
$this->pdo = new PDO(
|
|
$dsn,
|
|
$username,
|
|
$password,
|
|
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
|
|
);
|
|
Logger::log(self::$logFile, "Подключение успешно!");
|
|
} catch (PDOException $e) {
|
|
$message = "Ошибка подключения:" . $e->getMessage();
|
|
Logger::log(self::$logFile, $message);
|
|
}
|
|
}
|
|
|
|
public function __destruct()
|
|
{
|
|
Logger::log(self::$logFile, "Подключение прервано!");
|
|
}
|
|
|
|
public function selectQuery(string $sql, array $params = []) : array
|
|
{
|
|
try {
|
|
$stmt = $this->pdo->prepare($sql);
|
|
// $params = array_values($params);
|
|
for ($i = 0; $i < count($params); $i++) {
|
|
$stmt->bindParam(":v".$i+1, $params[$i]);
|
|
}
|
|
$stmt->execute();
|
|
$array = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
|
} catch (PDOException $e) {
|
|
$message = "Ошибка запроса:" . $e->getMessage();
|
|
Logger::log(self::$logFile, $message);
|
|
} finally {
|
|
return $array;
|
|
}
|
|
}
|
|
|
|
public function insertQuery(string $sql, array $params)
|
|
{
|
|
try {
|
|
$stmt = $this->pdo->prepare($sql);
|
|
for ($i = 0; $i < count($params); $i++) {
|
|
$stmt->bindParam(":spec_code".$i+1, $params[$i]['spec_code']);
|
|
$stmt->bindParam(":spec_name".$i+1, $params[$i]['spec_name']);
|
|
$stmt->bindParam(":edu_forms".$i+1, $params[$i]['edu_forms']);
|
|
$stmt->bindParam(":edu_level".$i+1, $params[$i]['edu_level']);
|
|
$stmt->bindParam(":contingent".$i+1, $params[$i]['contingent']);
|
|
$stmt->bindParam(":org_id".$i+1, $params[$i]['org_id']);
|
|
$stmt->bindParam(":spec_id".$i+1, $params[$i]['spec_id']);
|
|
}
|
|
$stmt->execute();
|
|
Logger::log(self::$logFile, "Запрос выполнен успешно!");
|
|
} catch (PDOException $e) {
|
|
$message = "Ошибка запроса:" . $e->getMessage();
|
|
Logger::log(self::$logFile, $message);
|
|
}
|
|
}
|
|
} |