-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphp_db.php
More file actions
145 lines (127 loc) · 3.12 KB
/
Copy pathphp_db.php
File metadata and controls
145 lines (127 loc) · 3.12 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
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
<?php
// A class that contains useful php functions that interact with mysql
class php_db
{
// the instance variables
private $conn;
private $host;
private $user;
private $password;
private $dbaseName;
private $debug;
private $status_fatal;
function __construct($username,$pass,$dbname)
{
$this->conn = false;
$this->host = 'turing'; //hostname
$this->user = $username;
$this->password = $pass;
$this->dbaseName = $dbname;
$this->port = '3306';
$this->debug = true;
$this->connect();
}
function __destruct()
{
$this->disconnect();
}
function connect()
{
if (!$this->conn)
{
try
{
$this->conn = new PDO('mysql:host='.$this->host.';dbname='.$this->dbaseName.'',
$this->user, $this->password,
array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
}
catch (Exception $e)
{
die('Error : ' . $e->getMessage());
}
if (!$this->conn)
{
$this->status_fatal = true;
echo 'Connection BD failed';
die();
}
else
{
$this->status_fatal = false;
}
}
return $this->conn;
}
function disconnect()
{
if ($this->conn)
{
$this->conn = null;
}
}
function query($query)
{
$result = $this->conn->prepare($query);
$ret = $result->execute();
if (!$ret)
{
echo 'PDO::errorInfo():';
echo '<br />';
echo "error SQL: $query";
die();
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$reponse = $result->fetchAll();
return $reponse;
}
function execute($query)
{
if (!$response = $this->conn->exec($query))
{
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
}
return $response;
}
function initDatabase()
{
try
{
}
catch (Exception $e)
{
die('Error : ' . $e->getMessage());
}
}
function insert($table, $values)
{
$result = $this->query("INSERT INTO " . $table . " " . " VALUES (" . $values . ")");
}
function printTable($arrValues)
{
try
{
echo '<table>';
// Output header row from keys.
echo '<tr>';
foreach($arrValues[0] as $key => $field)
echo '<th>' . $key . '</th>';
echo '</tr>';
// Output data rows from keys.
foreach ($arrValues as $row)
{
echo '<tr>';
foreach($row as $key => $field)
echo '<td>' . $field . '</td>';
echo '</tr>';
}
echo '</table>';
}
catch (Exception $e)
{
die('Error : ' . $e->getMessage());
}
}
}