forked from surveyjs/surveyjs-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
postgresdbadapter.php
112 lines (101 loc) · 3.64 KB
/
postgresdbadapter.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
class PostgresDBAdapter {
private $dbh;
public function __construct($config = null) {
$this->dbh = new PDO("pgsql:host=dataserver;port=5432;dbname=surveyjs;user=postgres;password=123456");
}
public function getObjectFromStorage($storageId) {
$sqlQuery = 'SELECT * FROM ' . $storageId;
$data = array();
$sql = $this->dbh->query($sqlQuery);
while($result = $sql->fetch(PDO::FETCH_ASSOC)) {
$data[$result['id']] = $result;
}
return $data;
}
public function getSurveys() {
$surveys = array("MySurvey1" => '{
"pages": [
{
"name": "page1",
"elements": [
{
"type": "radiogroup",
"choices": [
"item1",
"item2",
"item3"
],
"name": "question from survey1"
}
]
}
]
}',
"MySurvey2" => '{
"pages": [
{
"name": "page1",
"elements": [
{
"type": "checkbox",
"choices": [
"item1",
"item2",
"item3"
],
"name": "question from survey2"
}
]
}
]
}' );
$result = $this->getObjectFromStorage('surveys');
if(count($result) == 0) {
$id1 = $this->addSurvey('MySurvey1');
$this->storeSurvey($id1, $surveys['MySurvey1']);
$id2 = $this->addSurvey('MySurvey2');
$this->storeSurvey($id2, $surveys['MySurvey2']);
$result = $surveys;
}
return $result;
}
public function getSurvey($id) {
$storage = $this->getSurveys();
return $storage[$id]['json'];
}
public function addSurvey($name) {
$sqlQuery = 'insert into surveys (name, json) values (\'' . $name . '\', \'{}\') RETURNING *';
$sql = $this->dbh->query($sqlQuery);
$result = $sql->fetch(PDO::FETCH_ASSOC);
return $result['id'];
}
public function storeSurvey($id, $json) {
$sqlQuery = 'update surveys set json=\'' . $json . '\' where id=\'' . $id . '\'';
$sql = $this->dbh->query($sqlQuery);
$result = $sql->fetch(PDO::FETCH_ASSOC);
return $result;
}
public function deleteSurvey($id) {
$this->dbh->exec('DELETE FROM surveys WHERE id=\'' . $id . '\'');
}
public function changeName($id, $name) {
//TODO
}
public function postResults($postId, $resultsJson) {
$sqlQuery = 'insert into results (postid, json) values (\'' . $postId . '\', \'' . $resultsJson . '\')';
$sql = $this->dbh->query($sqlQuery);
$result = $sql->fetch(PDO::FETCH_ASSOC);
return $result['id'];
}
public function getResults($postId) {
$sqlQuery = 'SELECT * FROM results WHERE postid=\'' . $postId . '\'';
$data = array();
$sql = $this->dbh->query($sqlQuery);
while($result = $sql->fetch(PDO::FETCH_ASSOC)) {
array_push($data, $result['json']);
}
return $data;
}
}
?>