90 lines
2.5 KiB
PHP
90 lines
2.5 KiB
PHP
<?php
|
|
|
|
namespace Bcs\Databaseinterface;
|
|
|
|
class SqlSrvClient implements DatabaseInterface
|
|
{
|
|
protected $connection;
|
|
|
|
public function __construct(string $serverName, string $database, string $username, string $password)
|
|
{
|
|
$connectionOptions = [
|
|
"Database" => $database,
|
|
"Uid" => $username,
|
|
"PWD" => $password,
|
|
"TrustServerCertificate" => "true",
|
|
];
|
|
$this->connection = sqlsrv_connect($serverName, $connectionOptions);
|
|
|
|
// Check if the connection is successful
|
|
if ($this->connection === false) {
|
|
throw new \Exception("Failed to connect to the database: " . print_r(sqlsrv_errors(), true));
|
|
}
|
|
}
|
|
|
|
private function fetchResults($stmt): array
|
|
{
|
|
$rows = [];
|
|
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
|
|
$rows[] = $row;
|
|
}
|
|
return $rows;
|
|
}
|
|
|
|
public function query(string $sql, array $parameters = []): array
|
|
{
|
|
$stmt = sqlsrv_prepare($this->connection, $sql, $parameters);
|
|
|
|
if (!sqlsrv_execute($stmt)) {
|
|
throw new \Exception("Query failed: " . print_r(sqlsrv_errors(), true));
|
|
}
|
|
|
|
$rows = $this->fetchResults($stmt);
|
|
sqlsrv_free_stmt($stmt); // Freeing the statement is important to prevent resource leaks.
|
|
|
|
return $rows;
|
|
}
|
|
|
|
public function executeProcedure(string $procedureName, array $parameters = []): bool
|
|
{
|
|
$sql = "EXEC $procedureName " . implode(', ', array_map(fn($p) => '?', $parameters));
|
|
$stmt = sqlsrv_prepare($this->connection, $sql, array_values($parameters));
|
|
|
|
return sqlsrv_execute($stmt);
|
|
}
|
|
|
|
public function beginTransaction(): void
|
|
{
|
|
sqlsrv_begin_transaction($this->connection);
|
|
}
|
|
|
|
public function commit(): void
|
|
{
|
|
sqlsrv_commit($this->connection);
|
|
}
|
|
|
|
public function rollBack(): void
|
|
{
|
|
sqlsrv_rollback($this->connection);
|
|
}
|
|
|
|
public function execute(string $sql, array $parameters): bool
|
|
{
|
|
$stmt = sqlsrv_prepare($this->connection, $sql, $parameters);
|
|
|
|
return sqlsrv_execute($stmt);
|
|
}
|
|
|
|
public function insert(string $table, array $data): bool
|
|
{
|
|
$columns = implode(', ', array_keys($data));
|
|
$values = implode(', ', array_map(fn($v) => '?', $data));
|
|
$sql = "INSERT INTO $table ($columns) VALUES ($values)";
|
|
|
|
$stmt = sqlsrv_prepare($this->connection, $sql, array_values($data));
|
|
|
|
return sqlsrv_execute($stmt);
|
|
}
|
|
}
|
|
|