75 lines
3.0 KiB
PHP
75 lines
3.0 KiB
PHP
<?php
|
|
namespace App\Library;
|
|
|
|
use App\Library\DatabaseConfig;
|
|
use PDOException;
|
|
use PDO;
|
|
class Database
|
|
{
|
|
private PDO $pdo;
|
|
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]
|
|
);
|
|
$log = date('Y-m-d H:i:s') . ' Подлючение к успешно!';
|
|
file_put_contents(__DIR__ . '/../database.log', $log . PHP_EOL, FILE_APPEND);
|
|
} catch (PDOException $e) {
|
|
$log = date('Y-m-d H:i:s') . " Ошибка подключения:" . $e->getMessage();
|
|
file_put_contents(__DIR__ . '/../database.log', $log . PHP_EOL, FILE_APPEND);
|
|
}
|
|
}
|
|
|
|
public function __destruct()
|
|
{
|
|
$log = date('Y-m-d H:i:s') . ' Подлючение прервано!';
|
|
file_put_contents(__DIR__ . '/../database.log', $log . PHP_EOL, FILE_APPEND);
|
|
}
|
|
|
|
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) {
|
|
$log = date('Y-m-d H:i:s') . " Ошибка запроса:" . $e->getMessage();
|
|
file_put_contents(__DIR__ . '/../database.log', $log . PHP_EOL, FILE_APPEND);
|
|
} 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();
|
|
$log = date('Y-m-d H:i:s') . " Запрос выполнен успешно!";
|
|
file_put_contents(__DIR__ . '/../database.log', $log . PHP_EOL, FILE_APPEND);
|
|
} catch (PDOException $e) {
|
|
$log = date('Y-m-d H:i:s') . " Ошибка запроса:" . $e->getMessage();
|
|
file_put_contents(__DIR__ . '/../database.log', $log . PHP_EOL, FILE_APPEND);
|
|
}
|
|
}
|
|
} |