*** Backup Mirror *** The web interface and JSON api for the ConnectedHumber Air Quality Monitoring Project. https://github.com/ConnectedHumber/Air-Quality-Web
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

55 lines
1.5 KiB

<?php
namespace AirQuality;
use \SBRL\TomlConfig;
use Psr\Container\ContainerInterface;
/**
* Holds the main database connection.
*/
class Database
{
// Whether the database connection should be read only or not.
// Defaults to true, as we don't need to write _anything_ to the database.
private const read_only = true;
private $connection;
private $pdo_options = [
// https://devdocs.io/php/pdo.setattribute
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
\PDO::ATTR_AUTOCOMMIT => false
];
function __construct(TomlConfig $in_settings) {
error_log("Created database instance");
$this->settings = $in_settings;
$this->connect(); // Connect automagically
}
public function connect() {
error_log($this->get_connection_string());
$this->connection = new \PDO(
$this->get_connection_string(),
$this->settings->get("database.username"),
$this->settings->get("database.password"),
$this->pdo_options
);
// Make this connection read-only
if(self::read_only)
$this->connection->query("SET SESSION TRANSACTION READ ONLY;");
}
public function query($sql, $variables = []) {
// FUTURE: Optionally cache prepared statements?
return $this->connection->prepare($sql)->execute($variables);
}
private function get_connection_string() {
return "{$this->settings->get("database.type")}:host={$this->settings->get("database.host")};dbname={$this->settings->get("database.name")};charset=utf8mb4";
}
}