-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.php
More file actions
79 lines (67 loc) · 2.05 KB
/
db.php
File metadata and controls
79 lines (67 loc) · 2.05 KB
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
<?php
declare(strict_types=1);
require 'vendor/autoload.php';
use Doctrine\DBAL\Query\QueryBuilder;
use Doctrine\DBAL\Tools\DsnParser;
use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Connection;
readonly class JournalEntry
{
public function __construct(
public string $title = 'no value given',
public string $contentBody = 'no value given'
) {
}
}
final class JournalDatabase
{
private Connection $_conn;
public function __construct(string $user = 'root', string $host = 'localhost', string $database = 'journal')
{
$this->_conn = DriverManager::getConnection((new DsnParser())->parse('mysqli://' . $user . '@' . $host . '/' . $database));
}
protected function getConnection(): Connection
{
return $this->_conn;
}
protected function getQueryBuilder(): QueryBuilder
{
return $this->getConnection()->createQueryBuilder();
}
public function insertJournalEntry(JournalEntry $journalEntry): int
{
//save new post to database
return $this->getQueryBuilder()
->insert('entries')
->setValue('title', '?')
->setValue('contentBody', '?')
->setParameter(0, $journalEntry->title)
->setParameter(1, $journalEntry->contentBody)
->executeStatement();
}
public function fetchDisplayJournalEntries(): array
{
return $this->getQueryBuilder()
->select('title', 'contentBody', 'created_time')
->from('entries')
->orderBy('created_time', 'DESC')
->setMaxResults(10)
->executeQuery()
->fetchAllAssociative();
}
public function fetchNumberOfJournalEntries(): int
{
return $this->getQueryBuilder()
->select('*')
->from('entries')
->executeQuery()
->rowCount();
}
public function getDBVersion(): mixed
{
return $this->getQueryBuilder()
->select('VERSION();')
->executeQuery()
->fetchFirstColumn()[0];
}
}