This repository was archived by the owner on Aug 20, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDatabase.php
executable file
·82 lines (72 loc) · 2.06 KB
/
Database.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
75
76
77
78
79
80
81
82
<?php
namespace EBM;
use \PDO;
class Database
{
/**
* @var PDO
*/
private $pdo;
public function __construct(string $db_name, string $db_host, string $db_user, string $db_password)
{
$this->pdo = new PDO("mysql:dbname=$db_name;host=$db_host", $db_user, $db_password);
}
/**
* Run a query against the database
* @param string $query SQL query to run
* @param bool $onlyOne Return a single result if true
* @return array|mixed
*/
public function query(string $query, bool $onlyOne = false)
{
$req = $this->pdo->query($query);
// No need to fetch for these operations
if (strpos($query, 'UPDATE') === 0
|| strpos($query, 'INSERT') === 0
|| strpos($query, 'DELETE') === 0
) {
return $req;
}
$req->setFetchMode(PDO::FETCH_OBJ);
if ($onlyOne) {
$res = $req->fetch();
} else {
$res = $req->fetchAll();
}
return $res;
}
/**
* Run a prepared statement against the database
* @param string $query SQL query to run, variable parts are replaced with `?`
* @param array $attributes Variables array, to replace the `?` with
* @param bool $onlyOne Return a single result if true
* @return array|mixed
*/
public function prepare(string $query, array $attributes, bool $onlyOne = false)
{
$req = $this->pdo->prepare($query);
$req->setFetchMode(PDO::FETCH_OBJ);
$res = $req->execute($attributes);
// No need to fetch for these operations
if (strpos($query, 'UPDATE') === 0
|| strpos($query, 'INSERT') === 0
|| strpos($query, 'DELETE') === 0
) {
return $res;
}
if ($onlyOne) {
$res = $req->fetch();
} else {
$res = $req->fetchAll();
}
return $res;
}
/**
* Get last inserted id
* @return string
*/
public function lastInsertId()
{
return $this->pdo->lastInsertId();
}
}