mirror of
https://github.com/ConnectedHumber/Air-Quality-Web
synced 2024-12-22 10:25:01 +00:00
Setup database connection. Phew, that took longer than expected!
This commit is contained in:
parent
e7e1cb83d2
commit
4ea28cdbff
3 changed files with 57 additions and 2 deletions
|
@ -8,8 +8,10 @@ class FetchData {
|
|||
private $validator;
|
||||
|
||||
public function __construct(
|
||||
\SBRL\TomlConfig $in_settings) {
|
||||
\SBRL\TomlConfig $in_settings,
|
||||
\AirQuality\Database $in_database) {
|
||||
$this->settings = $in_settings;
|
||||
$this->database = $in_database;
|
||||
$this->validator = new \AirQuality\Validator($_GET);
|
||||
}
|
||||
|
||||
|
|
46
logic/Database.php
Normal file
46
logic/Database.php
Normal file
|
@ -0,0 +1,46 @@
|
|||
<?php
|
||||
|
||||
namespace AirQuality;
|
||||
|
||||
/**
|
||||
* 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(\SBRL\TomlConfig $in_settings) {
|
||||
$this->settings = $in_settings;
|
||||
}
|
||||
|
||||
public function connect() {
|
||||
$this->connection = new \PDO(
|
||||
$this->get_connection_string(),
|
||||
$this->settings->get("database.username"),
|
||||
$this->settings->get("database.password"),
|
||||
);
|
||||
// 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";
|
||||
}
|
||||
}
|
|
@ -7,8 +7,15 @@
|
|||
# Settings that control the database, or the connection to it
|
||||
|
||||
type = "mysql" # MariaDB. MySQL servers might work too, but no promises.
|
||||
database_name = "aq_db"
|
||||
|
||||
# The host that the database is running on. Both IP addresses & domain names are fine :-)
|
||||
host = "localhost"
|
||||
# The database to use.
|
||||
name = "aq_db"
|
||||
|
||||
# The username to connect with
|
||||
username = "user"
|
||||
# the password to connect with
|
||||
password = "Define_in_custom_config_file"
|
||||
|
||||
[routing]
|
||||
|
|
Loading…
Reference in a new issue