-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDatabaseConnection.php
75 lines (64 loc) · 1.98 KB
/
DatabaseConnection.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
<?php namespace Acme;
use Exception;
use PDO;
/**
* Class DatabaseConnection
* @package Acme
* Simple DB singleton to run basic queries that we need.
*/
class DatabaseConnection {
protected $connection;
private function __construct(){
try {
$pdo = new PDO('sqlite:db.sqlite');
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex){
echo 'Cannot connect to database';
exit(1);
}
$this->connection = $pdo;
}
public static function get(){
static $database = null;
if($database == null){
$database = new DatabaseConnection();
}
return $database;
}
public function addUser($parameters){
$sql = 'INSERT INTO Users (`name`, `ccnum`, `limit`, `is_valid`) values(:name, :cardNumber, :limit, :is_valid)';
return $this->connection->prepare($sql)->execute($parameters);
}
public function fetchUserByName($name){
$row = null;
$result = $this->connection->query('SELECT * FROM Users WHERE Users.Name = "' . $name . '"', PDO::FETCH_ASSOC);
if($result){
$row = $result->fetch(PDO::FETCH_ASSOC);
}
return $row;
}
public function updateBalanceForUser($user){
$result = $this->connection->query('UPDATE Users SET Balance="' . $user['Balance'] . '" WHERE Users.id = "' . $user['id'] . '"');
return $result;
}
public function truncate(){
$sql = 'DELETE from Users';
return $this->connection->prepare($sql)->execute();
}
public function removeUserByName($name){
$result = $this->connection->query('DELETE FROM Users WHERE Users.Name = "' . $name . '"');
return $result;
}
public function fetchAllUsers(){
$sql = 'SELECT * FROM Users ORDER BY Users."Name"';
$result = $this->connection->query($sql,PDO::FETCH_ASSOC);
$rows = array();
if($result){
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$rows[] = $row;
}
}
return $rows;
}
}