Skip to content

Commit

Permalink
Create class Database for better access to PDO
Browse files Browse the repository at this point in the history
With this new class things like transactions are possible for the first time
  • Loading branch information
felix-schindler committed Oct 27, 2022
1 parent e481f36 commit f268d40
Showing 1 changed file with 75 additions and 0 deletions.
75 changes: 75 additions & 0 deletions Backend/Core/Data/Database.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<?php

/**
* This class allow a more direct access to all Database
* classes for easier access to things like transactions
* @since 2.0.0
*/
class Database extends PDO
{
private PDOStatement $query;

/**
* Opens the connection to the DB automatically
*
* @throws PDOException If the connection can't be established
*/
public function __construct()
{
parent::__construct('mysql:host=' . DB_HOST . '; dbname=' . DB_NAME, DB_USER, DB_PASS);
}

/**
* Executes an SQL query
*
* @param string $queryStr SQL query as string
* @param array<string,string> $values Escaped values
* @throws PDOException When anything goes wrong
* @return bool Whether the query was executed successfully
*/
public function execute(string $queryStr, array $values): bool
{
$this->query = $this->prepare($queryStr);

if ($this->query !== false)
return $this->query->execute($values);
return false;
}

/**
* Reads data (row by row) from database
* Access returned value via $return['ColumnName']
*
* @see https://bugs.php.net/bug.php?edit=2&id=44341 Always string values!
* @throws PDOException When anything goes wrong
* @return array<string,string>|null Result as array - null on failure
*/
public function fetch(): ?array
{
$this->query->setFetchMode(PDO::FETCH_ASSOC); // Fetch into array
if (($result = $this->query->fetch()) !== false)
return $result;
return null;
}

/**
* Reads data (all rows) from database
*
* @see https://bugs.php.net/bug.php?edit=2&id=44341 Always string values!
* @return array<array<int|string,string>> Null on error, array with values (as string!) otherwise (PDO::FETCH_ASSOC)
*/
public function fetchAll(): array
{
return $this->query->fetchAll(PDO::FETCH_ASSOC);
}

/**
* Counts the effected rows of the last query
*
* @return integer Effected rows
*/
public function count(): int
{
return $this->query->rowCount();
}
}

0 comments on commit f268d40

Please sign in to comment.