49 lines
1.4 KiB
PHP
49 lines
1.4 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]
|
|
);
|
|
print("Подлючено успешно!\n");
|
|
} catch (PDOException $e) {
|
|
echo "Ошибка подключения:". $e->getMessage() . "\n";
|
|
}
|
|
}
|
|
|
|
public function __destruct()
|
|
{
|
|
echo "Подключение прервано!\n";
|
|
}
|
|
|
|
public function executeQuery(string $sql, array $params) : array|null
|
|
{
|
|
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) {
|
|
echo "Ошибка запроса: " . $e->getMessage() . "\n";
|
|
} finally {
|
|
return $array;
|
|
}
|
|
}
|
|
} |