source: trunk/Database.php

Last change on this file was 32, checked in by chronos, 5 years ago
  • Modified: Improved code formatting.
File size: 7.0 KB
Line 
1<?php
2
3// Extended database class
4// Date: 2016-01-11
5
6function microtime_float()
7{
8 list($usec, $sec) = explode(" ", microtime());
9 return (float)$usec + (float)$sec;
10}
11
12class DatabaseResult
13{
14 var $PDOStatement;
15 var $num_rows = 0;
16
17 function fetch_assoc()
18 {
19 return $this->PDOStatement->fetch(PDO::FETCH_ASSOC);
20 }
21
22 function fetch_array()
23 {
24 return $this->PDOStatement->fetch(PDO::FETCH_BOTH);
25 }
26
27 function fetch_row()
28 {
29 return $this->PDOStatement->fetch(PDO::FETCH_NUM);
30 }
31}
32
33class Database
34{
35 var $Prefix;
36 var $Functions;
37 var $Type;
38 var $PDO;
39 var $Error;
40 var $insert_id;
41 var $LastQuery;
42 var $ShowSQLError;
43 var $ShowSQLQuery;
44 var $LogSQLQuery;
45 var $LogFile;
46
47 function __construct()
48 {
49 $this->Prefix = '';
50 $this->Functions = array('NOW()', 'CURDATE()', 'CURTIME()', 'UUID()');
51 $this->Type = 'mysql'; // mysql, pgsql
52 $this->Error = '';
53 $this->LastQuery = '';
54 $this->ShowSQLError = false;
55 $this->ShowSQLQuery = false;
56 $this->LogSQLQuery = false;
57 $this->LogFile = dirname(__FILE__).'/../../Query.log';
58 }
59
60
61 function Connect($Host, $User, $Password, $Database)
62 {
63 if ($this->Type == 'mysql') $ConnectionString = 'mysql:host='.$Host.';dbname='.$Database;
64 else if ($this->Type == 'pgsql') $ConnectionString = 'pgsql:dbname='.$Database.';host='.$Host;
65 else $ConnectionString = '';
66 try {
67 $this->PDO = new PDO($ConnectionString, $User, $Password);
68
69 } catch (Exception $E)
70 {
71 unset($this->PDO);
72 throw new Exception($E->getMessage());
73 }
74 }
75
76 function Disconnect()
77 {
78 unset($this->PDO);
79 }
80
81 function Connected()
82 {
83 return isset($this->PDO);
84 }
85
86 function select_db($Database)
87 {
88 $this->query('USE `'.$Database.'`');
89 }
90
91 function query($Query)
92 {
93 if (!$this->Connected()) throw new Exception(T('Not connected to database'));
94 if (($this->ShowSQLQuery == true) or ($this->LogSQLQuery == true)) $QueryStartTime = microtime_float();
95 $this->LastQuery = $Query;
96 //echo('a'.$this->ShowSQLQuery.'<'.$QueryStartTime.', '.microtime_float());
97 if (($this->ShowSQLQuery == true) or ($this->LogSQLQuery == true))
98 $Duration = ' ; '.round(microtime_float() - $QueryStartTime, 4). ' s';
99 if ($this->LogSQLQuery == true)
100 file_put_contents($this->LogFile, $Query.$Duration."\n", FILE_APPEND);
101 if ($this->ShowSQLQuery == true)
102 echo('<div style="border-bottom-width: 1px; border-bottom-style: solid; '.
103 'padding-bottom: 3px; padding-top: 3px; font-size: 12px; font-family: Arial;">'.$Query.$Duration.'</div>'."\n");
104 $Result = new DatabaseResult();
105 $Result->PDOStatement = $this->PDO->query($Query);
106 if ($Result->PDOStatement)
107 {
108 $Result->num_rows = $Result->PDOStatement->rowCount();
109 $this->insert_id = $this->PDO->lastInsertId();
110 } else
111 {
112 $this->Error = $this->PDO->errorInfo();
113 $this->Error = $this->Error[2];
114 if (($this->Error != '') and ($this->ShowSQLError == true))
115 echo('<div><strong>SQL Error: </strong>'.$this->Error.'<br />'.$Query.'</div>');
116 throw new Exception('SQL Error: '.$this->Error.', Query: '.$Query);
117 }
118 return $Result;
119 }
120
121 function select($Table, $What = '*', $Condition = 1)
122 {
123 return $this->query('SELECT '.$What.' FROM `'.$this->Prefix.$Table.'` WHERE '.$Condition);
124 }
125
126 function delete($Table, $Condition)
127 {
128 $this->query('DELETE FROM `'.$this->Prefix.$Table.'` WHERE '.$Condition);
129 }
130
131 function insert($Table, $Data)
132 {
133 $this->query($this->GetInsert($Table, $Data));
134 $this->insert_id = $this->PDO->lastInsertId();
135 }
136
137 function GetInsert($Table, $Data)
138 {
139 $Name = '';
140 $Values = '';
141 foreach ($Data as $Key => $Value)
142 {
143 $Name .= ',`'.$Key.'`';
144 if (!in_array($Value, $this->Functions))
145 {
146 if (is_null($Value)) $Value = 'NULL';
147 else $Value = $this->PDO->quote($Value);
148 }
149 $Values .= ','.$Value;
150 }
151 $Name = substr($Name, 1);
152 $Values = substr($Values, 1);
153 return 'INSERT INTO `'.$this->Prefix.$Table.'` ('.$Name.') VALUES('.$Values.')';
154 }
155
156 function update($Table, $Condition, $Data)
157 {
158 $this->query($this->GetUpdate($Table, $Condition, $Data));
159 }
160
161 function GetUpdate($Table, $Condition, $Data)
162 {
163 $Values = '';
164 foreach ($Data as $Key => $Value)
165 {
166 if (!in_array($Value, $this->Functions))
167 {
168 if (is_null($Value)) $Value = 'NULL';
169 else $Value = $this->PDO->quote($Value);
170 }
171 $Values .= ', `'.$Key.'`='.$Value;
172 }
173 $Values = substr($Values, 2);
174 return 'UPDATE `'.$this->Prefix.$Table.'` SET '.$Values.' WHERE ('.$Condition.')';
175 }
176
177 function replace($Table, $Data)
178 {
179 $Name = '';
180 $Values = '';
181 foreach ($Data as $Key => $Value)
182 {
183 if (!in_array($Value, $this->Functions))
184 {
185 if (is_null($Value)) $Value = 'NULL';
186 else $Value = $this->PDO->quote($Value);
187 }
188 $Name .= ',`'.$Key.'`';
189 $Values .= ','.$Value;
190 }
191 $Name = substr($Name, 1);
192 $Values = substr($Values, 1);
193 //echo('REPLACE INTO `'.$this->Prefix.$Table.'` ('.$Name.') VALUES ('.$Values.')<br />');
194 $this->query('REPLACE INTO `'.$this->Prefix.$Table.'` ('.$Name.') VALUES('.$Values.')');
195 //echo($this->error().'<br>');
196 }
197
198 function charset($Charset)
199 {
200 $this->query('SET NAMES "'.$Charset.'"');
201 }
202
203 function real_escape_string($Text)
204 {
205 return addslashes($Text);
206 }
207
208 function quote($Text)
209 {
210 return $this->PDO->quote($Text);
211 }
212
213 public function __sleep()
214 {
215 return array('LastQuery');
216 }
217
218 public function __wakeup()
219 {
220 }
221
222 public function Transaction($Queries)
223 {
224 $this->PDO->beginTransaction();
225 foreach ($Queries as $Query)
226 {
227 $Statement = $this->PDO->prepare($Query);
228 $Statement->execute();
229 }
230 if (!$this->PDO->commit())
231 {
232 $this->Error = $this->PDO->errorInfo();
233 $this->Error = $this->Error[2];
234 if (($this->Error != '') and ($this->ShowSQLError == true))
235 echo('<div><strong>SQL Error: </strong>'.$this->Error.'<br />'.$Query.'</div>');
236 throw new Exception('SQL Error: '.$this->Error.', Query: '.$Query);
237 }
238 }
239}
240
241function TimeToMysqlDateTime($Time)
242{
243 if ($Time == NULL) return NULL;
244 else return date('Y-m-d H:i:s', $Time);
245}
246
247function TimeToMysqlDate($Time)
248{
249 if ($Time == NULL) return NULL;
250 else return date('Y-m-d', $Time);
251}
252
253function TimeToMysqlTime($Time)
254{
255 if ($Time == NULL) return NULL;
256 else return date('H:i:s', $Time);
257}
258
259function MysqlDateTimeToTime($DateTime)
260{
261 if ($DateTime == '') return NULL;
262 $Parts = explode(' ', $DateTime);
263 $DateParts = explode('-', $Parts[0]);
264 $TimeParts = explode(':', $Parts[1]);
265 $Result = mktime($TimeParts[0], $TimeParts[1], $TimeParts[2], $DateParts[1], $DateParts[2], $DateParts[0]);
266 return $Result;
267}
268
269function MysqlDateToTime($Date)
270{
271 if ($Date == '') return NULL;
272 return MysqlDateTimeToTime($Date.' 0:0:0');
273}
274
275function MysqlTimeToTime($Time)
276{
277 if ($Time == '') return NULL;
278 return MysqlDateTimeToTime('0000-00-00 '.$Time);
279}
Note: See TracBrowser for help on using the repository browser.