Come on, you know you want to buy me a beer!

So, it's 9pm on a Thursday night.

I just spent the past 2 hours putting together a quick PHP MySQL Class for a friend.
His requirements were VERY simple. He needed to select, update, insert, delete. Also known as CRUD : Create, Read, Update, Delete. I just wrapped it up and finished some very basic testing. Essentially it's incredibly easy to follow and use. It's very well documented (a big thank you to ZendStudio for the simplicity of documenting PHP Classes and PHP Functions).

Come to think of it, if it's of any use, buy me a beer! He is :) - He just doesn't know it yet.

I'll start with the MySQL SQL File to create a very simple table. Then you'll see the class, and then finally we'll shoot straight into some examples of how to use this bad boy.

First, create a database on your server, and run this script against it:

Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `position` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `name`, `position`) VALUES
(1, 'Joe Bloggs', 'Owner'),
(2, 'Jane Bloggs', 'Wife');



Now, you should have a table in your database called users, which has 3 columns (id, name, position). Within that table there should be 2 records. Joe and Jane.

Next, here's the PHP Class / along with the relevant PHP Public Functions and PHP Private Functions to make it work.

Code:
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
<?php
/**
 * 
 * Class MyDB
 * 
 * A simple, yet very efficient class for managing common MySQL interactions
 * with PHP.
 * 
 * This is a work in progress and I'll be adding to it.
 * 
 * Questions?
 * 
 *      Email me : rogere84 ( at ) gmail ( dot ) com
 * 
 *  SQL Script for examples:
 *  

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `position` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `name`, `position`) VALUES
(1, 'Joe Bloggs', 'Owner'),
(2, 'Jane Bloggs', 'Wife');

 * 
 * 
 * 
 * @author Roger E Thomas - September 2011
 * @website http://www.rogerethomas.com
 * @copyright 2011 Roger E Thomas
 * 
 * 
 */
class MyDB {
    
    private 
$_Con;
    
    const 
MYSQL_HOST '127.0.0.1'// Database Host
    
    
const MYSQL_USER 'your mysql username'// Database User
    
    
const MYSQL_PASS 'your mysql password'// Database Password
    
    
const MYSQL_NAME 'your mysql database name'// Database Name
    

    
function __construct() {

        
$this->_Con mysql_connect(self::MYSQL_HOST,self::MYSQL_USER,self::MYSQL_PASS);
        
        if (!
$this->_Con) {
            exit(
'Connection failed to MySQL host <b>' self::MYSQL_HOST '</b>');
        }
        
        
mysql_select_db(self::MYSQL_NAME,$this->_Con);
        
        if (
mysql_error()) {
            exit(
'Connection to <b>' self::MYSQL_NAME '</b> failed.');
        }

    }
    
    
/**
     * 
     * selectFrom
     * 
     * Simple method to select a result set from a mysql database
     * 
     * @param str $table
     * @param str / array $columns
     * @param array $where
     * @param boolean $like
     * @param str $orderby
     * @param str $direction
     * @param int $limit
     * @param int $offset
     * @return array('sql' => $SQL, 'num' => $num, 'result' => $result);
     * 
     * 
     * 
     * 
     * Example Usage 1 :
     * 
     * <code>
     * require 'MyDB.php';
     * $con = new MyDB();
     * $query = $con -> selectFrom("users", $columns = null, $where = null, $like = false, $orderby = "id", $direction = "DESC", $limit = null, $offset = null);
     * </code>
     * 
     * Generated SQL:
     * SELECT * FROM users ORDER BY id DESC
     * 
     * Return Example:
     * 
        Array
        (
            [sql] => SELECT * FROM users ORDER BY id DESC
            [num] => 2
            [result] => Array
                (
                    [0] => Array
                        (
                            [id] => 2
                            [name] => Jane Bloggs
                            [position] => Wife
                        )
        
                    [1] => Array
                        (
                            [id] => 1
                            [name] => Joe Bloggs
                            [position] => Owner
                        )
        
                )
        
        )
     * 
     * Example Usage 2 :
     * <code>
     * require 'MyDB.php';
     * $con = new MyDB();
     * $query = $con->selectFrom($table = "people", $columns = array('id','name','position'), $where = array('name'=>'Joe Bloggs'), $like = false, $orderby = "id", $direction = "DESC", $limit = 2, $offset = 1);
     * </code>
     * 
     * This would run the following SQL statement:
     * SELECT id, name, position FROM users WHERE name='Joe Bloggs' ORDER BY id DESC LIMIT 1, 2
     * 
     * 
     * 
     * Example Usage 3 :
     * 
     * <code>
     * require 'MyDB.php';
     * $con = new MyDB();
     * $query = $con->selectFrom($table = "users", $columns = array('id','name','position'), $where = array('name'=>'Joe'), $like = true, $orderby = "id", $direction = "DESC", $limit = 2, $offset = 1);
     * </code>
     * 
     * This would run the following SQL statement:
     * 
     * SELECT id, name, position FROM users WHERE name LIKE '%Joe%' ORDER BY id DESC LIMIT 1, 2
     * 
     * 
     * 
     * Return Value:
     * array(
     *         sql => The actual SQL statement that this file ran against the database,
     *         num => The number of results fetched from the database,
     *         result => each row set in its own array
     * )
     * 
     */
    
public function selectFrom($table$columns null$where null$like false$orderby null$direction null$limit null$offset null) {

        
$SQL "SELECT ";
        if (
$columns != null) {
            if(
is_array($columns)) { $cols implode(", ",$columns); }
            else { 
$cols $columns; }
            
$SQL.= $cols." ";
        }
        else {
            
$SQL.= "* ";
        }
        
$SQL.= "FROM ".$table;
        
        if (
$where != null) {
            
$SQL.=" WHERE";
            if (
$like == true) {
                
$whe $this->_helperWhereLikeGenerate($where);
            }
            else {
                
$whe $this->_helperWhereEqualsGenerate($where);
            }
            
$SQL.= $whe;
        }
        if (
$direction != null && $orderby != null) {
            if (
strtolower($direction) == "asc" || strtolower($direction) == "desc") {
                
$order " ORDER BY ".$orderby." ".$direction;
                
$SQL .= $order;
            }
        }
        if (
$limit != null) {
            if (
$offset == null) {
                
$lim " LIMIT ".$limit;
                
$SQL .= $lim;
            }
            else {
                
$lim " LIMIT ".$offset.", ".$limit;
                
$SQL .= $lim;
            }
        }

        
$exec mysql_query($SQL,$this->_Con);

        
$num mysql_num_rows($exec);
        if (
$num != 0) {
            
$result = array();
            while (
NULL != ($row mysql_fetch_assoc($exec))) {
                
$thisset = array();
                foreach (
$row as $key => $val) {
                        
$thisset[$key] = $val;
                }
                
$result[] = $thisset;
            }
        }
        
        
$returnarray = array('sql' => $SQL'num' => $num'result' => $result);
        
        return 
$returnarray;

    }
    
    
/**
     * insertInto
     * 
     * Simple method to insert a row of data into a mysql
     * database. This function relies on a mysql_insert_id()
     * to be returned so you must have an auto increment
     * field in the table.
     * 
     * @param str $table
     * @param array $fields
     * 
     * Example Usage 1 :
     * 
     * <code>
     * require 'MyDB.php';
     * $con = new MyDB();
     * $query = $con -> insertInto("users", $fields = array("id" => "", "name" => "John Doe", "position" => "Unknown"));
     * </code>
     * 
     * Generated SQL:
     * INSERT INTO users (id, name, position) VALUES ('', 'John Doe', 'Unknown')
     * 
     * Note that we place id into the array put into the
     * function but leave its value as empty. This is our
     * auto-increment columns which we rely on to identify
     * a successful insertion.
     * 
     * Return Example: (Success)
     * 
        Array
        (
            [status] => success
            [id] => 4
        )
     * 
     * 
     * Return Example: (Failure)
     * 
        Array
        (
            [status] => failure
            [id] => 0
        )
     * 
     * 
     */
    
public function insertInto($table null$fields) {

        
$cleanfields $this->_helperCleanFields($fields);
                
        
$inserts $this->_helperExtractFieldsValues($cleanfields);
        
        
$SQL "INSERT INTO ";
        
$SQL.= $table " ";
        
$SQL.= $inserts['fields'] . " ";
        
$SQL.= "VALUES ";
        
$SQL.= $inserts['values'] . " ";

        
mysql_query($SQL$this->_Con);

        
$id mysql_insert_id($this->_Con);
        
        if (isset(
$id) && is_numeric($id) && $id != 0) {
            
$status "success";
        }
        else {
            
$status "failure";
        }
        
        
$insertid $id;
        
        
$return = array('status' => $status'id' => $insertid);
        
        return 
$return;
        
    }
    
    
/**
     * updateTable
     * 
     * Simple method to update a MySQL table giving specific reference
     * to values to set, and under what conditions (WHERE).
     * 
     * Also supports %LIKE% when $like = true
     * 
     * @param str $table
     * @param array $fields
     * @param array $where
     * @param boolean $like
     * 
     * 
     * Example Usage 1 :
     * 
     * <code>
     * require 'MyDB.php';
     * $con = new MyDB();
     * $query = $con -> updateTable("users", $fields = array("name" => "a","position" => "b"), $where = array("id"=>"2"), $like = true);
     * </code>
     * 
     * Generated SQL:
     * UPDATE users SET name='a', position='b' WHERE id LIKE '%2%' 
     * 
     * Return Example: (Success)
     * 
        Array
        (
            [sql] => UPDATE users SET name='a', position='b' WHERE id LIKE '%2%' 
            [status] => success
            [affected] => 1
        )
     * 
     * 
     * Return Example: (Failure)
     * 
        Array
        (
            [sql] => UPDATE users SET nosuchfield='a', position='b' WHERE id LIKE '%2%' 
            [status] => failure
            [affected] => 0
        )
     * 
     * 
     */
    
public function updateTable($table$fields$where null$like false) {

        
$cleanfields $this->_helperCleanFields($fields);
        
        if (
$where != null) {
            
$wherebegin " WHERE";
            if (
$like == false) {
                
$wherecommand $this->_helperWhereEqualsGenerate($where);
            }
            else {
                
$wherecommand $this->_helperWhereLikeGenerate($where);
            }
            
$wherecommand $wherebegin.$wherecommand;
        }
        else {
            
$wherecommand "";
        }
        
    
        
$updates $this->_helperExtractUpdateValues($cleanfields);
        
        
$SQL "UPDATE ";
        
$SQL.= $table " ";
        
$SQL.= $updates "";
        
$SQL.= $wherecommand " ";
        
        
mysql_query($SQL$this->_Con);

        
$num mysql_affected_rows($this->_Con);
        
        if (isset(
$num) && is_numeric($num) && $num != && $num != -1) {
            
$status "success";
        }
        else {
            
$status "failure";
        }
        
        
$affected $num;
        
        
$return = array('sql' => $SQL'status' => $status'affected' => $affected);
        
        return 
$return;
        
    }
    
    
    
/**
     * deleteFrom
     * 
     * A simple method to delete data from a mysql database.
     * This requires no real input other than a table name,
     * HOWEVER... If you don't specify the $where array or the
     * $limit then you will get some nasty surprises. I would
     * strongly suggest you run this against a dummy database
     * before testing on a production system.
     * 
     * @param str $table
     * @param array $where
     * @param boolean $like
     * @param int $limit
     * 
     * Example Usage 1 : (Success)
     * 
     * <code>
     * require 'MyDB.php';
     * $con = new MyDB();
     * $query = $con -> deleteFrom("users", $where = array('name'=>'John Doe','position'=>'Unknown'), $like = false, $limit = 1);
     * </code>
     * 
     * Generated SQL:
     * DELETE FROM users WHERE name='John Doe' AND position='Unknown' LIMIT 1
     * 
     * Return Example: (Success)
     * 
        Array
        (
            [sql] => DELETE FROM users WHERE name='John Doe' AND position='Unknown' LIMIT 1
            [status] => success
            [affected] => 1
        )
     * 
     * Example Usage 2 : (Success)
     * 
     * <code>
     * require 'MyDB.php';
     * $con = new MyDB();
     * $query = $con -> deleteFrom("users", $where = array('name'=>'John','position'=>'Unknown'), $like = true, $limit = 1);
     * </code>
     * 
     * Generated SQL:
     * DELETE FROM users WHERE name LIKE '%John%' AND position LIKE '%Unknown%' LIMIT 1
     * 
     * Return Example: (Success)

        Array
        (
            [sql] => DELETE FROM users WHERE name LIKE '%John%' AND position LIKE '%Unknown%' LIMIT 1
            [status] => success
            [affected] => 1
        )
     * 
     * 
     * Example Usage 3 : (Failure)
     * 
     * <code>
     * require 'MyDB.php';
     * $con = new MyDB();
     * $query = $con -> deleteFrom("users", $where = array('nosuchfield'=>'John','position'=>'Unknown'), $like = false, $limit = 1);
     * </code>
     * 
     * Generated SQL:
     * DELETE FROM users WHERE name LIKE '%John%' AND position LIKE '%Unknown%' LIMIT 1
     * 
     * Return Example: (Failure)

        Array
        (
            [sql] => DELETE FROM users WHERE nosuchfield='John' AND position='Unknown' LIMIT 2
            [status] => failure
            [affected] => -1
        )
     * 
     */
    
public function deleteFrom($table$where null$like false$limit 1) {
        
        
$SQL "DELETE ";
        
$SQL.= "FROM ".$table;
        
        if (
$where != null) {
            
$SQL.=" WHERE";
            if (
$like == true) {
                
$whe $this->_helperWhereLikeGenerate($where);
            }
            else {
                
$whe $this->_helperWhereEqualsGenerate($where);
            }
            
$SQL.= $whe;
        }

        if (
$limit != null) {
            
$lim " LIMIT ".$limit;
            
$SQL .= $lim;
        }

        
mysql_query($SQL,$this->_Con);
        
        
$num mysql_affected_rows($this->_Con);
        
        if (isset(
$num) && is_numeric($num) && $num != && $num != -1) {
            
$status "success";
        }
        else {
            
$status "failure";
        }
        
        
$affected $num;
        
        
$return = array('sql' => $SQL'status' => $status'affected' => $affected);
        
        return 
$return;
        
    }

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
/**
     * A helper function to generate x LIKE %y% AND y LIKE %z%
     * @param array $where
     * @return str
     */
    
private function _helperWhereLikeGenerate($where) {
        
        if (!empty(
$where)) {
            
$whe "";
            
$i 0;
            foreach (
$where as $wKey => $wVal) {
                
$i++;
                if (
$i != 1) { $wheAdd " AND "; }
                else { 
$wheAdd " "; }
                
$whe .= $wheAdd.$wKey " LIKE '%".mysql_real_escape_string($wVal,$this->_Con)."%'";
            }
        }
        else {
            
$whe "";
        }
        
        return 
$whe;
    
    }
    
    
/**
     * A helper function to generate x = y AND y = z
     * @param array $where
     * @return str
     */
    
private function _helperWhereEqualsGenerate($where) {
        
        if (!empty(
$where)) {
            
$whe "";
            
$i 0;
            foreach (
$where as $wKey => $wVal) {
                
$i++;
                if (
$i != 1) { $wheAdd " AND "; }
                else { 
$wheAdd " "; }
                
$whe .= $wheAdd.$wKey "='".mysql_real_escape_string($wVal,$this->_Con)."'";
            }
        }
        else {
            
$whe "";
        }
        
        return 
$whe;
    
    }
    
    
/**
     * A helper function to cleanse values
     * @param array $fields
     * @return array clean key => values
     */
    
private function _helperCleanFields($fields) {
        
        
$cleanfields = array();
        
        foreach (
$fields as $fkey => $fval) {
            
            
$cleanfields[$fkey] = mysql_real_escape_string($fval,$this->_Con);
            
        }
        
        return 
$cleanfields;
    
    }
    
    
/**
     * A helper function to extract field names
     * and values from an array of clean variables.
     * @param array $cleanfields
     * @return array ( fields, values )
     */
    
private function _helperExtractFieldsValues($cleanfields) {

        
$return = array();
        
        if (!empty(
$cleanfields)) {
            
$keys array_keys($cleanfields);
            
$vals array_values($cleanfields);
            
            
$insertFields implode(", ",$keys);
            
$insertFields "(".$insertFields.")";
            
$insertValues implode("', '",$vals);
            
$insertValues "('".$insertValues."')";
    
            
$return['fields'] = $insertFields;
            
$return['values'] = $insertValues;
        }

        return 
$return;
        
    }
    
    
/**
     * A helper function to extract the cleansed fields
     * into a string for the UPDATE command
     * @param array $cleanfields
     */
    
private function _helperExtractUpdateValues($cleanfields) {
        
        
$return "";
        
        if (!empty(
$cleanfields)) {
            
$return .= "SET";
            
$i 0;
            foreach (
$cleanfields as $key => $value) {
                
$i++;
                if (
$i != 1){ $begin ","; }
                else { 
$begin ""; }
                
$return .= $begin." " $key "='".$value."'";
                
            }
        }
        
        return 
$return;
        
    }
    
}



Here's how you use the class to SELECT FROM MySQL:

Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
    
require_once 'MyDB.php';
    
$con = new MyDB();
    
    
$query $con -> selectFrom("users"$columns null$where null$like false$orderby "id"$direction "DESC"$limit null$offset null);
    
    echo 
"<h3>Result Set</h3>";
    echo 
"<p>Number Results: <b>".$query['num']."</b></p>";
    echo 
"<pre>";
    
print_r($query);
    echo 
"</pre>";


Here's how you place data into the database ( INSERT INTO MySQL ):

Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
    
require_once 'MyDB.php';
    
$con = new MyDB();
    
    
$query $con -> insertInto("users"$fields = array("id" => """name" => "John Doe""position" => "Unknown"));
    
    echo 
"<h3>Result</h3>";
    echo 
"<p>Status: <b>".$query['status']."</b><br />";
    echo 
"Inserted ID: <b>".$query['id']."</b></p>";
    echo 
"<pre>";
    
print_r($query);
    echo 
"</pre>";


Here's how you update a MySQL database record ( UPDATE table SET ):

Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
    
require_once 'MyDB.php';
    
$con = new MyDB();
    
    
$query $con -> updateTable("users"$fields = array("name" => "b","position" => "c"), $where = array("id"=>"1"), $like true);
    
    echo 
"<h3>Result</h3>";
    echo 
"<p>Status: <b>".$query['status']."</b><br />";
    echo 
"Affected: <b>".$query['affected']." Rows</b></p>";
    echo 
"<pre>";
    
print_r($query);
    echo 
"</pre>";


And finally, here's how you delete a record from MySQL ( DELETE FROM table ):

Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
    
require_once 'MyDB.php';
    
$con = new MyDB();
    
    
$query $con -> deleteFrom("users"$where = array('name'=>'John','position'=>'Unknown'), $like true$limit 1);
    
    echo 
"<h3>Result</h3>";
    echo 
"<p>Status: <b>".$query['status']."</b><br />";
    echo 
"Affected: <b>".$query['affected']." Rows</b></p>";
    echo 
"<pre>";
    
print_r($query);
    echo 
"</pre>";


Now... You're still reading. Good. You need to adjust some things within the class to make them all work. Mainly, make sure you set the CONSTANTS within the class file. You'll find them at around line 46 to 52 (dependant on what browser you're using to view this site as I've been told some browsers screw up the line numbers royally).

The lines look like this:

Code:
1
2
3
4
5
6
7
8
9
10

    const MYSQL_HOST = '127.0.0.1'; // Database Host 
     
    const MYSQL_USER = 'your mysql username'; // Database User 
     
    const MYSQL_PASS = 'your mysql password'; // Database Password 
     
    const MYSQL_NAME = 'your mysql database name'; // Database Name


Now, just in case you can't for some reason make this work, take my copy. You can download it here: http://www.rogerethomas.com/j_downloads/MyDB.class.zip

And again, please - If you like this, come on, buy me a beer

Comments


Your Name:

Email Address: (won't be published)

Comments: (no HTML allowed)

 

There are no comments yet.

 

 

 

 

 

 

Latest Posts