commit | author | age
|
1a98b6
|
1 |
<?php |
JK |
2 |
class Database { |
|
3 |
private $pdo; |
|
4 |
private $getByIdStatement; |
|
5 |
private $getByNumStatement; |
|
6 |
private $addStatement; |
|
7 |
|
|
8 |
public function __construct($file) { |
|
9 |
$this->pdo = new PDO('sqlite:'.$file); |
|
10 |
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); |
|
11 |
|
|
12 |
$this->pdo->query('CREATE TABLE IF NOT EXISTS vehicles ( |
|
13 |
id INT PRIMARY KEY, |
|
14 |
num INT UNIQUE, |
|
15 |
weight INT |
|
16 |
)'); |
|
17 |
|
|
18 |
$this->getByIdStatement = $this->pdo->prepare('SELECT num, weight FROM vehicles WHERE id=? LIMIT 1'); |
|
19 |
$this->getByNumStatement = $this->pdo->prepare('SELECT id, weight FROM vehicles WHERE num=? LIMIT 1'); |
|
20 |
$this->addStatement = $this->pdo->prepare('INSERT OR REPLACE INTO vehicles (id, num, weight) VALUES (?, ?, ?)'); |
|
21 |
} |
|
22 |
|
|
23 |
public function getById($id) { |
|
24 |
$this->getByIdStatement->execute([$id]); |
|
25 |
return $this->getByIdStatement->fetch(); |
|
26 |
} |
|
27 |
|
|
28 |
public function getByNum($num) { |
|
29 |
$st = $this->getByNumStatement->execute([(int)substr($num, 2)]); |
|
30 |
return $this->getByNumStatement->fetch(); |
|
31 |
} |
|
32 |
|
|
33 |
public function clear() { |
|
34 |
$this->pdo->query('DELETE FROM vehicles'); |
|
35 |
} |
|
36 |
|
|
37 |
public function add($id, $num, $weight) { |
|
38 |
$this->addStatement->execute([$id, $num, $weight]); |
|
39 |
} |
|
40 |
|
|
41 |
public function addMapping($mapping) { |
|
42 |
$weight = count($mapping); |
|
43 |
foreach($mapping as $id => $vehicle) { |
|
44 |
$this->add($id, (int)substr($vehicle['num'], 2), $weight); |
|
45 |
} |
|
46 |
} |
|
47 |
} |