sveden-parser/app/library/Database.php

74 lines
2.6 KiB
PHP
Raw Normal View History

2024-08-08 12:32:27 +02:00
<?php
namespace App\Library;
use App\Library\DatabaseConfig;
2024-08-16 14:00:37 +02:00
use App\Library\Logger;
2024-08-08 12:32:27 +02:00
use PDOException;
use PDO;
class Database
2024-08-08 12:32:27 +02:00
{
private PDO $pdo;
2024-08-16 14:00:37 +02:00
private static $logFile = 'database.log';
public function __construct(DatabaseConfig $config)
2024-08-08 12:32:27 +02:00
{
try {
$dsn = $config->getDsn();
$username = $config->getUsername();
$password = $config->getPassword();
$this->pdo = new PDO(
2024-08-08 12:32:27 +02:00
$dsn,
$username,
$password,
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
2024-08-16 14:00:37 +02:00
Logger::log(self::$logFile, "Подключение успешно!");
2024-08-08 12:32:27 +02:00
} catch (PDOException $e) {
2024-08-16 14:00:37 +02:00
$message = "Ошибка подключения:" . $e->getMessage();
Logger::log(self::$logFile, $message);
2024-08-08 12:32:27 +02:00
}
}
public function __destruct()
{
2024-08-16 14:00:37 +02:00
Logger::log(self::$logFile, "Подключение прервано!");
2024-08-08 12:32:27 +02:00
}
public function selectQuery(string $sql, array $params = []) : array
2024-08-08 12:32:27 +02:00
{
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) {
2024-08-16 14:00:37 +02:00
$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();
2024-08-16 14:00:37 +02:00
Logger::log(self::$logFile, "Запрос выполнен успешно!");
} catch (PDOException $e) {
2024-08-16 14:00:37 +02:00
$message = "Ошибка запроса:" . $e->getMessage();
Logger::log(self::$logFile, $message);
}
}
2024-08-08 12:32:27 +02:00
}