database-class
Code (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
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
<?
// *** ------------------------------------------------------------------------------------ *** //
// *** Class.Database, a object which can work around the database handling *** //
// *** Orginally created: 5 november 2005 *** // *** //
// *** Author: Kees Schepers & Mike de Klerk *** //
// *** Last edit: 5 november 2005: creation :) *** //
// *** Platform PHP4.x *** //
// *** ------------------------------------------------------------------------------------ *** //
class dbClass {
var $host;
var $username;
var $password;
var $database;
var $executedQuerys = 0;
var $connection;
var $errors;
var $cssClass;
function dbClass($host = 'localhost', $username, $password, $database) {
// ---
// Check if variables ain't empty, if is not empty then connect to database
// ---
if(!empty($username) AND !empty($host) AND !empty($database)) {
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->_dbConnect();
}
else
{
trigger_error('I can not connect with empty parameters; username, password and database.', E_USER_NOTICE);
}
$this->cssClass = 'debug';
}
function _dbConnect() {
// ---
// Just connect
// ---
if( $this->connection = mysql_connect($this->host, $this->username, $this->password) ) {
if( mysql_select_db($this->database, $this->connection) ) {
trigger_error('Connection set and database selected!',E_USER_NOTICE);
return TRUE;
} else {
trigger_error('Error when selecting database.',E_USER_NOTICE);
return FALSE;
}
} else {
trigger_error('Error when connection to mysql.',E_USER_NOTICE);
return FALSE;
}
}
function dbDisconnect() {
// ---
// Disconnect database connection
// ---
mysql_close($this->connection);
}
function insertRow($table,$value) {
// ---
// With this function you can insert a record to a table which looks to the keys of
// the values array and the fields in the table and replaces the value..
// ---
$sql = 'INSERT INTO '.$table.'
(';
// ---
// Which and how many fields does the table have?
// ---
$result = $this->execQuery( 'SELECT * FROM '.$table );
$total_fields = $this->numFields( $result );
for($i=1;$i<$total_fields;$i++) {
if($total_fields-$i != 1 ) {
$sql .= '`'.$this->fieldName($result,$i).'`,';
} else {
$sql .= '`'.$this->fieldName($result,$i).'`';
}
}
$sql .= ')
VALUES
(';
for($i=1;$i<$total_fields;$i++) {
if($total_fields-$i != 1 ) {
$sql .= '"'.$value[$this->fieldName($result,$i)].'",';
} else {
$sql .= '"'.$value[$this->fieldName($result,$i)].'"';
}
}
$sql .= ')';
return $this->execQuery($sql);
}
function deleteRow($table,$id) {
// ---
// This functions deletes a record from the database.
// ---
return $this->execQuery('DELETE FROM `'.$table.'` WHERE `id`="'.$id.'"');
}
function updateRow($table,$value=array(),$id) {
//--------
// function to automaticly update a (set of) row(s) and looks to the $value array for a key which equals to table field name and
// replaces the value in the mysql table..
// Which fields does the table have? And are there values posted?
//--------
if( count($value) > 0 ) {
$result = mysql_query( 'SELECT * FROM `'.$table.'`' );
$total_fields = $this->numFields( $result );
$sql = 'UPDATE `'.$table.'` SET ';
for($i=1;$i<$total_fields;$i++)
{
if( !empty($value[$this->fieldName($result,$i)]) )
{
$sql .= '`'.$this->fieldName($result,$i).'`="'.$value[$this->fieldName($result,$i)].'", ';
}
}
$sql = substr($sql,0,(strlen($sql)-2));
$sql .= ' WHERE id="'.$id.'"';
// ---
// returns the affected rows by succeeding. Else false with a trigger error
// ---
return $this->execQuery($sql);
} else {
trigger_error('values array has no keys and values when using $obj_db->updateRow()',E_USER_NOTICE);
return FALSE;
}
}
function selectRows($table,$criterion) {
$sql = 'SELECT * FROM '.$table.' '.$criterion;
$result = $this->execQuery($sql);
if($this->numRows($result) > 0 ) {
return $this->fetchResult($result);
} else {
return FALSE;
}
}
function insertId() {
return mysql_insert_id();
}
function affectedRows($result) {
return mysql_affected_rows($result);
}
function numRows($result) {
return mysql_num_rows($result);
}
function numFields($result) {
return mysql_num_fields($result);
}
function fieldName($result,$numindex) {
return mysql_field_name($result,$numindex);
}
function execQuery($query) {
// ---
// affected rows only returns a value with INSERT, UPDATE or DELETE.
// ---
if($result = mysql_query($query,$this->connection) OR trigger_error('Failed execute query in db_obj. Error: '.$this->sqlError().' Query: '.$query, E_USER_WARNING) ) {
trigger_error('Query succeed with syntax: '.$query,E_USER_NOTICE);
if(strpos($query, 'SELECT') !== FALSE ) {
$this->executedQuerys++;
return $result;
} elseif( (strpos($query, 'INSERT') !== FALSE) OR (strpos($query, 'UPDATE') !== FALSE) OR (strpos($query, 'DELETE') !== FALSE) ) {
// ---
// affected rows returned.
// ---
return $this->affectedRows($this->connection);
} else {
$this->executedQuerys++;
return TRUE;
}
} else {
return FALSE;
}
}
function fetchResult($result) {
// ---
// This functions fetches the result of a query, in one standard way, this will learn us to work with one method!
// ---
if( $this->numRows($result) > 0 ) {
// ---
// We make our own array, with a numeric index for a record and a text index for the fields !
// ---
$records = array();
while( $record = mysql_fetch_array($result) ) {
$records[]=$record;
}
return $records;
} else {
trigger_error('$obj_db->fetchResult() was trying to fetch a query qith no records as result!',E_USER_NOTICE);
return FALSE;
}
}
function oneRowResult($result,$row) {
if( is_numeric($row) ) {
return mysql_result($result,$row);
} else {
trigger_error('Second parameter with function oneRowResult in $obj_db was not numeric',E_USER_NOTICE);
}
}
function sqlError() {
// ---
// Gives a error of the failed result, and then sets it in the error var of this object..
// ---
if( DEBUG === TRUE ) {
$this->errors [] = mysql_error($this->connection);
}
return mysql_error($this->connection);
}
function debug() {
// ---
// This function drops debug info, of query results.
// ---
echo '<div class="'.$this->cssClass.'" style="margin-top:10px;">';
if(count($this->errors) > 0) {
foreach($this->errors AS $errno => $error) {
echo 'Error NR: '.$errno.' '.$error.' <br />';
}
} else {
echo 'No database errors to print!';
}
echo '<br />'.$this->executedQuerys.' query\'s executed.';
echo '</div>';
}
}
// ---
// Inialiseer een database verbinding
// ---
$database = New dbClass('localhost','testuser','testpassword','testdatabase');
// ---
// ### De functie insertRow() ###
// Stel je hebt een pagina met een html-form en als er op submit geklikt word genereer je de volgende gegevens:
// ---
$_POST['name'] = 'test';
$_POST['age'] = '16';
$_POST['birthdate'] = '22-07-1986';
$_POST['hobbys'] = 'TV Kijken, werken, vrouwen, bier, programming, fitness and many more';
// ---
// Oke stel, dat je een nieuwe record wil toevoegen in de database en je hebt volgende kolommen in je database (name,age,birthdate,hobbys)
// Dan zou je ook lekker een lange query kunnen bouwen, maar je zou ook het volgende kunnen doen:
// ---
$database->insertRow('tabelnaam',$_POST);
// ---
// De functie "insertRow()" gaat alle velden af, en kijkt of deze bestaan in de tabel, indien ja, dan zet hij deze waarden.
// Waarom doet hij dit? omdat je misschien een gepost veld hebt dat $_POST['submit'] heeft, dan zou hij die ook proberen in te voegen
// en krijg je een dikke sql error
// ---
// ---
// Stel je hebt een form op je site, en je wilt dat een gebruiker zijn gegevens kan wijzigen, dan zou je de volgende functie kunnen gebruiken:
// ---
$database->updateRow('tabelnaam',$_POST,$_GET['id']);
// ---
// Deze functie doet bijna hetzelfde als insertRow, alleen dat hij een update uitvoert op de record id, die meegegeven is als 3e parameter.
// ---
// ---
// Stel je wilt een aantal gegevens fetchen, bijvoorbeeld een lijstje van je gebruikers, dan kun je dit alsvolgt doen:
// ---
$result = $database->execQuery('SELECT * FROM users');
if( $database->numRows( $result ) > 0 ) {
$user = $database->fetchResult($result);
// ---
// Laat nu de users zien.
// ---
echo '<table>';
for( $userNR=0; $userNR<count($user); $userNR++ ) {
echo '<tr>';
echo ' <td>'.$user[$userNR]['name'].'</td>';
echo ' <td>'.$user[$userNR]['age'].'</td>';
echo ' <td>'.$user[$userNR]['birtdate'].'</td>';
echo '</tr>';
}
echo '</table>';
} else {
echo 'Er zijn geen resultaten.';
}
// ---
// Stel dat je nog aan het debuggen bent doe je dit:
// ---
$database->debug();
// ---
// Deze functie print allerlei handige informatie
// ---
// ---
// en altijd aan het einde van je script netjes je database verbinding sluiten!
// ---
$database->dbDisconnect();
?>
// *** ------------------------------------------------------------------------------------ *** //
// *** Class.Database, a object which can work around the database handling *** //
// *** Orginally created: 5 november 2005 *** // *** //
// *** Author: Kees Schepers & Mike de Klerk *** //
// *** Last edit: 5 november 2005: creation :) *** //
// *** Platform PHP4.x *** //
// *** ------------------------------------------------------------------------------------ *** //
class dbClass {
var $host;
var $username;
var $password;
var $database;
var $executedQuerys = 0;
var $connection;
var $errors;
var $cssClass;
function dbClass($host = 'localhost', $username, $password, $database) {
// ---
// Check if variables ain't empty, if is not empty then connect to database
// ---
if(!empty($username) AND !empty($host) AND !empty($database)) {
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->_dbConnect();
}
else
{
trigger_error('I can not connect with empty parameters; username, password and database.', E_USER_NOTICE);
}
$this->cssClass = 'debug';
}
function _dbConnect() {
// ---
// Just connect
// ---
if( $this->connection = mysql_connect($this->host, $this->username, $this->password) ) {
if( mysql_select_db($this->database, $this->connection) ) {
trigger_error('Connection set and database selected!',E_USER_NOTICE);
return TRUE;
} else {
trigger_error('Error when selecting database.',E_USER_NOTICE);
return FALSE;
}
} else {
trigger_error('Error when connection to mysql.',E_USER_NOTICE);
return FALSE;
}
}
function dbDisconnect() {
// ---
// Disconnect database connection
// ---
mysql_close($this->connection);
}
function insertRow($table,$value) {
// ---
// With this function you can insert a record to a table which looks to the keys of
// the values array and the fields in the table and replaces the value..
// ---
$sql = 'INSERT INTO '.$table.'
(';
// ---
// Which and how many fields does the table have?
// ---
$result = $this->execQuery( 'SELECT * FROM '.$table );
$total_fields = $this->numFields( $result );
for($i=1;$i<$total_fields;$i++) {
if($total_fields-$i != 1 ) {
$sql .= '`'.$this->fieldName($result,$i).'`,';
} else {
$sql .= '`'.$this->fieldName($result,$i).'`';
}
}
$sql .= ')
VALUES
(';
for($i=1;$i<$total_fields;$i++) {
if($total_fields-$i != 1 ) {
$sql .= '"'.$value[$this->fieldName($result,$i)].'",';
} else {
$sql .= '"'.$value[$this->fieldName($result,$i)].'"';
}
}
$sql .= ')';
return $this->execQuery($sql);
}
function deleteRow($table,$id) {
// ---
// This functions deletes a record from the database.
// ---
return $this->execQuery('DELETE FROM `'.$table.'` WHERE `id`="'.$id.'"');
}
function updateRow($table,$value=array(),$id) {
//--------
// function to automaticly update a (set of) row(s) and looks to the $value array for a key which equals to table field name and
// replaces the value in the mysql table..
// Which fields does the table have? And are there values posted?
//--------
if( count($value) > 0 ) {
$result = mysql_query( 'SELECT * FROM `'.$table.'`' );
$total_fields = $this->numFields( $result );
$sql = 'UPDATE `'.$table.'` SET ';
for($i=1;$i<$total_fields;$i++)
{
if( !empty($value[$this->fieldName($result,$i)]) )
{
$sql .= '`'.$this->fieldName($result,$i).'`="'.$value[$this->fieldName($result,$i)].'", ';
}
}
$sql = substr($sql,0,(strlen($sql)-2));
$sql .= ' WHERE id="'.$id.'"';
// ---
// returns the affected rows by succeeding. Else false with a trigger error
// ---
return $this->execQuery($sql);
} else {
trigger_error('values array has no keys and values when using $obj_db->updateRow()',E_USER_NOTICE);
return FALSE;
}
}
function selectRows($table,$criterion) {
$sql = 'SELECT * FROM '.$table.' '.$criterion;
$result = $this->execQuery($sql);
if($this->numRows($result) > 0 ) {
return $this->fetchResult($result);
} else {
return FALSE;
}
}
function insertId() {
return mysql_insert_id();
}
function affectedRows($result) {
return mysql_affected_rows($result);
}
function numRows($result) {
return mysql_num_rows($result);
}
function numFields($result) {
return mysql_num_fields($result);
}
function fieldName($result,$numindex) {
return mysql_field_name($result,$numindex);
}
function execQuery($query) {
// ---
// affected rows only returns a value with INSERT, UPDATE or DELETE.
// ---
if($result = mysql_query($query,$this->connection) OR trigger_error('Failed execute query in db_obj. Error: '.$this->sqlError().' Query: '.$query, E_USER_WARNING) ) {
trigger_error('Query succeed with syntax: '.$query,E_USER_NOTICE);
if(strpos($query, 'SELECT') !== FALSE ) {
$this->executedQuerys++;
return $result;
} elseif( (strpos($query, 'INSERT') !== FALSE) OR (strpos($query, 'UPDATE') !== FALSE) OR (strpos($query, 'DELETE') !== FALSE) ) {
// ---
// affected rows returned.
// ---
return $this->affectedRows($this->connection);
} else {
$this->executedQuerys++;
return TRUE;
}
} else {
return FALSE;
}
}
function fetchResult($result) {
// ---
// This functions fetches the result of a query, in one standard way, this will learn us to work with one method!
// ---
if( $this->numRows($result) > 0 ) {
// ---
// We make our own array, with a numeric index for a record and a text index for the fields !
// ---
$records = array();
while( $record = mysql_fetch_array($result) ) {
$records[]=$record;
}
return $records;
} else {
trigger_error('$obj_db->fetchResult() was trying to fetch a query qith no records as result!',E_USER_NOTICE);
return FALSE;
}
}
function oneRowResult($result,$row) {
if( is_numeric($row) ) {
return mysql_result($result,$row);
} else {
trigger_error('Second parameter with function oneRowResult in $obj_db was not numeric',E_USER_NOTICE);
}
}
function sqlError() {
// ---
// Gives a error of the failed result, and then sets it in the error var of this object..
// ---
if( DEBUG === TRUE ) {
$this->errors [] = mysql_error($this->connection);
}
return mysql_error($this->connection);
}
function debug() {
// ---
// This function drops debug info, of query results.
// ---
echo '<div class="'.$this->cssClass.'" style="margin-top:10px;">';
if(count($this->errors) > 0) {
foreach($this->errors AS $errno => $error) {
echo 'Error NR: '.$errno.' '.$error.' <br />';
}
} else {
echo 'No database errors to print!';
}
echo '<br />'.$this->executedQuerys.' query\'s executed.';
echo '</div>';
}
}
// ---
// Inialiseer een database verbinding
// ---
$database = New dbClass('localhost','testuser','testpassword','testdatabase');
// ---
// ### De functie insertRow() ###
// Stel je hebt een pagina met een html-form en als er op submit geklikt word genereer je de volgende gegevens:
// ---
$_POST['name'] = 'test';
$_POST['age'] = '16';
$_POST['birthdate'] = '22-07-1986';
$_POST['hobbys'] = 'TV Kijken, werken, vrouwen, bier, programming, fitness and many more';
// ---
// Oke stel, dat je een nieuwe record wil toevoegen in de database en je hebt volgende kolommen in je database (name,age,birthdate,hobbys)
// Dan zou je ook lekker een lange query kunnen bouwen, maar je zou ook het volgende kunnen doen:
// ---
$database->insertRow('tabelnaam',$_POST);
// ---
// De functie "insertRow()" gaat alle velden af, en kijkt of deze bestaan in de tabel, indien ja, dan zet hij deze waarden.
// Waarom doet hij dit? omdat je misschien een gepost veld hebt dat $_POST['submit'] heeft, dan zou hij die ook proberen in te voegen
// en krijg je een dikke sql error
// ---
// ---
// Stel je hebt een form op je site, en je wilt dat een gebruiker zijn gegevens kan wijzigen, dan zou je de volgende functie kunnen gebruiken:
// ---
$database->updateRow('tabelnaam',$_POST,$_GET['id']);
// ---
// Deze functie doet bijna hetzelfde als insertRow, alleen dat hij een update uitvoert op de record id, die meegegeven is als 3e parameter.
// ---
// ---
// Stel je wilt een aantal gegevens fetchen, bijvoorbeeld een lijstje van je gebruikers, dan kun je dit alsvolgt doen:
// ---
$result = $database->execQuery('SELECT * FROM users');
if( $database->numRows( $result ) > 0 ) {
$user = $database->fetchResult($result);
// ---
// Laat nu de users zien.
// ---
echo '<table>';
for( $userNR=0; $userNR<count($user); $userNR++ ) {
echo '<tr>';
echo ' <td>'.$user[$userNR]['name'].'</td>';
echo ' <td>'.$user[$userNR]['age'].'</td>';
echo ' <td>'.$user[$userNR]['birtdate'].'</td>';
echo '</tr>';
}
echo '</table>';
} else {
echo 'Er zijn geen resultaten.';
}
// ---
// Stel dat je nog aan het debuggen bent doe je dit:
// ---
$database->debug();
// ---
// Deze functie print allerlei handige informatie
// ---
// ---
// en altijd aan het einde van je script netjes je database verbinding sluiten!
// ---
$database->dbDisconnect();
?>