This repository was archived by the owner on Jun 8, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDatabase.class.php
74 lines (66 loc) · 2.18 KB
/
Database.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
/**
* Usage :
* $dbLink = new Database();
*
* $req1 = $dbLink->select('SELECT * FROM users');
* $req2 = $dbLink->select('SELECT * FROM users WHERE username = :username', ['username' => 'rigwild']);
* $req3 = $dbLink->execute('INSERT INTO users VALUES (:username), ['username' => 'rigwild']);
*
* The link with the database is established once on each reload.
*
* @author rigwild - https://github.com/rigwild
* @see https://gist.github.com/rigwild/5d4660f3f6f979171496a11e548020d9
*/
require_once 'DatabaseConfig.class.php';
class Database {
private $dbCredentials = null;
private $connection = null;
public function __construct() {
$this->dbCredentials = Config::$DatabaseCredentials;
}
private function connect() {
if ($this->connection !== null)
return $this->connection;
$dbInfos = $this->dbCredentials['SGBD']
.':host='.$this->dbCredentials['host']
.';port='.$this->dbCredentials['port']
.';dbname='.$this->dbCredentials['dbName']
.';charset=utf8';
$username = $this->dbCredentials['username'];
$password = $this->dbCredentials['password'];
$conn = new PDO($dbInfos, $username, $password);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$this->connection = $conn;
return $conn;
}
/**
* Execute a select query
* @param query the SQL query to execute
* @param parametersArray an array of parameters
*
* @return boolean the result of the query
*/
public function select($query, $parametersArray = []) {
$conn = $this->connect();
$stmt = $conn->prepare($query);
if ($stmt->execute($parametersArray))
return $stmt->fetchAll();
return null;
}
/**
* Execute a query that doesn't return any tuples
* @param query the SQL query to execute
* @param parametersArray an array of parameters
*
* @return boolean the query worked
*/
public function execute($query, $parametersArray = []) {
$conn = $this->connect();
$stmt = $conn->prepare($query);
return ($stmt->execute($parametersArray));
}
}
?>