Category Archives: PHP + mySQL

PHP Web Programing Language & mySQL Databases

Charts Class that i wrote before 7 years – just found on phpclasses.org – PHP 4

Written by Garry Lachman (Admin). Filed under PHP + mySQL. Tagged , , , , , , , , . .

Hey….
Just found one of my first classes that i wrote, before 7 years and still popular on phpclasses.org

grchart.class.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
<?php
/*
    GrCharts 0.1 pre-alpha.
    ---------------------------------------------------------------
    Under GNU/GPL.
    ---------------------------------------------------------------
    Change log:
    ---------------------------------------------------------------
    12/10/2004 - Added new functions (Style(); and chartsarray();)
    6/10/2004 - First Version: 0.1 pre-alpha
    ---------------------------------------------------------------
    Build by Garry Lachman.
*/

class grchart {
    var $last_id;
    var $total;
    var $precent_array;
    var $chart_array;
    var $style;
    var $log;
   
    function start($value) {
        $this->total = $value;
        $this->log .= "GrChart started with total: $value<br>";
        $this->last_id = "0";
        $this->log .= "Last ID set to \"0\"<br>";
    }
   
    function ch_style($value) {
        $this->style = $value;
        $this->log .="Style set to $value<br>";
    }
   
    function add_chart($value) {
        $current_id = $this->last_id + 1;
        $total = $this->total;
        $precent = ($value/$total) * 100;
        $this->precent_array[$current_id] = $precent;
        $this->last_id++;
       
        $this->log .= "---------------------------------------------<br>";
        $this->log .= "Added chart : <br>";
        $this->log .= "Value: $value <br>";
        $this->log .= "Precents: $precent%<br>";
        $this->log .= "Last ID set to \"$current_id\"<br>";
        $this->log .= "---------------------------------------------<br>";
    }
   
    function init() {
        $last_id = $this->last_id;
        $style = $this->style;
        $i = 1;
        $x = 0;
        while($i <= $last_id) {
            $work_id = $i;
            $work_precent = $this->precent_array[$work_id];
            while($x <= $work_precent) {
                $buffer = $buffer . "|";
                $x++;
            }
            $this->chart_array[$work_id] = $buffer;
            $buffer = "";
           
            $this->log .= "Created HTML code for chart no` $work_id<br>";
        $i++;
        $x=0;
        }
       
        $this->log .= "\n Init complite, all HTML code created <br>";
    }
   
    function style($value) {
        $style = $this->style;
        $chart = $this->chart_array[$value];
        $precent = $this->precent_array[$value];
        switch($style) {
            case red:
                $chart = str_replace("|", "<img src='images/red.gif'>", $chart);
                break;
               
            case green:
                $chart = str_replace("|", "<img src='images/green.gif'>", $chart);
                break;
               
            case pre:
                $chart = str_replace("|", " ", $chart);
                $chart .= "  (" . number_format($precent, 2, '.', '') . "%)";
                break;
        }
        return $chart;
       
    }
   
    function chart($value) {
        $chart = $this->style($value);
        return $chart;
    }
   
    function chartsarray() {
        $last_id = $this->last_id;
        $i = 0;
        $value = 0;
       
        while($i <= $last_id) {
            $style = $this->style;
            $chart = $this->chart_array[$value];
            $precent = $this->precent_array[$value];
            if ($chart <> "") {
                $chart = $this->style($value);
            $chartsarray[$value] = $chart;    
            }
            $value++;
            $i++;
        }    
    return $chartsarray;
    }
   
    function echo_log() {
        return $this->log;
    }

}
?>

Lets test it…

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
<?php
include("grchart.class.php");
$chart = new grchart;

$chart->start(100);

$chart->add_chart("20");
$chart->add_chart("60");
$chart->add_chart("10");
$chart->add_chart("10");

$chart->init();

?>
<table width="100%" border="1">
<TR>
<TD>Red Style</TD>
<?
$chart->ch_style("red");
?>
</TR>
<TR>
<td><? print $chart->chart(1) ?></td>
</TR>
<TR>
<td><? print $chart->chart(2) ?></td>
</TR>
<TR>
<td><? print $chart->chart(3) ?></td>
</TR>
<TR>
<td><? print $chart->chart(4) ?></td>
</TR>
</table>

<br>

<table width="100%" border="1">
<TR>
<TD>Green Style</TD>
<?
$chart->ch_style("green");
?>
</TR>
<TR>
<td><? print $chart->chart(1) ?></td>
</TR>
<TR>
<td><? print $chart->chart(2) ?></td>
</TR>
<TR>
<td><? print $chart->chart(3) ?></td>
</TR>
<TR>
<td><? print $chart->chart(4) ?></td>
</TR>
</table>

<br>

<table width="100%" border="1">
<TR>
<TD>Pre Style</TD>
<?
$chart->ch_style("pre");
?>
</TR>
<TR>
<td><? print $chart->chart(1) ?></td>
</TR>
<TR>
<td><? print $chart->chart(2) ?></td>
</TR>
<TR>
<td><? print $chart->chart(3) ?></td>
</TR>
<TR>
<td><? print $chart->chart(4) ?></td>
</TR>
</table>
<br>
<?
$chart->ch_style("green");
$ca = $chart->chartsarray();
print $ca[1] . "<br>". $ca[2];
?>

Enjot it ;)
The project on phpclasses.php
http://www.phpclasses.org/package/1934-PHP-Generate-share-bar-charts-in-HTML.html

Have a nice day ;)
Garry Lachman

Share

mySQL Layer that i wrote years ago

Written by Garry Lachman (Admin). Filed under PHP + mySQL. Tagged , , , , , , , , . .

Hi,
Before years ago i wrote a secured mySQL Layer.
I`m now actually using it now, but its works great years…

First of all the Settings Singleton Class:
Settings.Class.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
<?php
/////////////////////////////////////////////////////////////////
/////////////////// Garry`s MySQL Class /////////////////////////
/////////////////////////////////////////////////////////////////
//////////////////      14/12/07        /////////////////////////
// THIS CLASS WRITTEN BY GARRY LACHMAN -> DRGARRY@GMAIL.COM    //
/////////////////////////////////////////////////////////////////

class Settings {
 
    var $mysql;
    var $security;
     
    function Settings ($directCall=true)
    {
        if ($directCall) {
            trigger_error("This Class is singleton!", E_USER_ERROR);
        }
    }
 
    function &getInstance()
    {
        static $instance;
        if (!is_object($instance)) {
            $instance = new Settings(false);
            $instance->fillValues();
        }
        return $instance;
    }
 
 
    // GETTERS
    function getMySQLSettings($node) {  return $this->mysql[$node]; }
    function getSecuritySettings($node) {   return $this->security[$node];  }
   
    // PRIVATE FUNCTIONS
    function fillValues() {
        // MYSQL
        $this->mysql['hostname'] = 'localhost';
        $this->mysql['username'] = 'root';
        $this->mysql['password'] = 'password';
        $this->mysql['database'] = 'db';
        $this->mysql['prefix'] = 'prefix_';
       
        // SECURITY - we don`t use this in mySQL Layer class
        $this->security['hash'] = 'sdfijh2p348y7yxd487*&%^ygog(&^9togI%R$(50))';
    }
 
}
?>

The mySQL Layer Class:

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
<?php
/////////////////////////////////////////////////////////////////
/////////////////// Garry`s MySQL Class /////////////////////////
/////////////////////////////////////////////////////////////////
//////////////////      14/12/07        /////////////////////////
// THIS CLASS WRITTEN BY GARRY LACHMAN -> DRGARRY@GMAIL.COM    //
/////////////////////////////////////////////////////////////////

require_once('./Settings.class.php');
class MySQL {
    // MySQL VARS
    var $mysql_link;
    var $mysql_host;
    var $mysql_username;
    var $mysql_password;
    var $mysql_database;   
    var $mysql_link_status = false;
    var $mysql_prefix;
   
    // VARS FOR LAST OPERATIONS
    var $query_result = Array();
    var $records_number;
   
    // CLASS VARS
    var $script_log;
    var $Settings;
    var $inited = false;
       
    function MySQL() {
        // LOADING SINGLETON INSTANCE OF SETTINGS
        $this->Settings =& Settings::getInstance();
       
        // LOADING SETTINGS FROM SETTINGS CLASS
        $this->mysql_host = $this->Settings->getMySQLSettings('hostname');
        $this->mysql_username = $this->Settings->getMySQLSettings('username');
        $this->mysql_password = $this->Settings->getMySQLSettings('password');
        $this->mysql_database = $this->Settings->getMySQLSettings('database');
        $this->mysql_prefix = $this->Settings->getMySQLSettings('prefix');
       
           
        $this->script_log .= "Constractor set settings\n";
        $this->inited = true;
        $this->script_log .= "Inited set to: " . $this->inited . "\n";
    }
   
    // PUBLIC FUNCTIONS
   
    function CustomQuerty($query)
    {
        $this->CheckConnection();
       
        $this->script_log .= "Query: " . $query . "\n";
       
        $result = mysql_query($query) or die($this->mysql_error_report());
       
        $this->script_log .= "Query executed\n";
       
        return $result;
    }
   
    function InsertQuerymassive($table, $insert_fields, $insert_values) {
        $this->CheckConnection();
       
        // BUILD SECURED QUERY - FOR SQL INJECTIONS PROTECTION
        $query = sprintf("INSERT INTO `%s` (", mysql_escape_string($table));
       
        $i=0;
       
        foreach($insert_fields as $arr) {
            if ($i > 0) {
                $query .= sprintf(", `%s`", mysql_escape_string($insert_fields[$i]));
            } else {
                $query .= sprintf("`%s`", mysql_escape_string($insert_fields[$i]));
            }
            $i++;
        }
       
       
       
        $i=0;
        foreach($insert_values as $arr) {
            $j=0;
            if ($i == 0)
            {
                $query .= ") VALUES (";
            }
            else
            {
                $query .= ", (";           
            }
            foreach($arr as $arr2)
            {
                if ($j > 0) {
                    $query .= sprintf(", '%s'", mysql_escape_string($arr2));
                } else {
                    $query .= sprintf("'%s'", mysql_escape_string($arr2));
                }
                $i++;
                $j++;
            }
            $query .= ")";
        }
   
        $this->script_log .= "Query: " . $query . "\n";
       
        $result = mysql_query($query) or die($this->mysql_error_report());
       
        $this->script_log .= "Query executed\n";
       
        return mysql_insert_id();
       
    }
   
   
    function InsertQuery($table, $insert_fields, $insert_values) {
        $this->CheckConnection();
        mysql_query("set character set 'utf8'");
        // BUILD SECURED QUERY - FOR SQL INJECTIONS PROTECTION
        $query = sprintf("INSERT INTO `%s` (", mysql_escape_string($table));
       
        $i=0;
       
        foreach($insert_fields as $arr) {
            if ($i > 0) {
                $query .= sprintf(", `%s`", mysql_escape_string($insert_fields[$i]));
            } else {
                $query .= sprintf("`%s`", mysql_escape_string($insert_fields[$i]));
            }
            $i++;
        }
        $query .= ") VALUES (";
       
       
        $i=0;
        foreach($insert_values as $arr) {
            if ($i > 0) {
                $query .= sprintf(", '%s'", mysql_escape_string($insert_values[$i]));
            } else {
                $query .= sprintf("'%s'", mysql_escape_string($insert_values[$i]));
            }
            $i++;
        }
        $query .= ")";
   
   
        $this->script_log .= "Query: " . $query . "\n";
       
        $result = mysql_query($query) or die($this->mysql_error_report());
       
        $this->script_log .= "Query executed\n";
       
        return mysql_insert_id();
       
    }
   
    function DeleteQuery($table, $where_field, $where_value, $opr=NULL)
    {
        $this->CheckConnection();
       
        $query = sprintf("DELETE FROM %s", mysql_escape_string($table));
               
        if (isset($where_field) && isset($where_value)) {
            $query .= " WHERE ";
            $i=0;
            foreach($where_field as $arr) {
                if ($i>0) {
                    $query .= sprintf(" %s `%s`='%s'",mysql_escape_string($opr[$i-1]),
                                                mysql_escape_string($where_field[$i]),
                                                mysql_escape_string($where_value[$i]));
                } else {
                    $query .= sprintf("`%s`='%s'", mysql_escape_string($where_field[$i]),
                                                mysql_escape_string($where_value[$i]));
                }
                $i++;
            }
        }
       
        $this->script_log .= "Query: " . $query . "\n";
       
       
        $result = mysql_query($query) or die($this->mysql_error_report());
        $this->script_log .= "Query executed\n";
    }
       
    function UpdateQuery($table, $update_fields, $update_values,
                            $where_field=NULL, $where_value=NULL, $opr=NULL) {
        $this->CheckConnection();
       
        // BUILD SECURED QUERY - FOR SQL INJECTIONS PROTECTION
        $query = sprintf("UPDATE `%s` SET ", mysql_escape_string($table));
       
        $i=0;
        foreach($update_fields as $arr) {
            /*if ($i > 0) {
                $query .= sprintf(", %s `%s`='%s'", mysql_escape_string($opr[$i-1]),
                                                    mysql_escape_string($update_fields[$i]),
                                                    mysql_escape_string($update_values[$i]));              
            } */

            if ($i > 0) {
                $query .= sprintf(", `%s`='%s'",    mysql_escape_string($update_fields[$i]),
                                                    mysql_escape_string($update_values[$i]));              
            } else {
                $query .= sprintf("`%s`='%s'", mysql_escape_string($update_fields[$i]),
                                                mysql_escape_string($update_values[$i]));
            }
            $i++;
        }
       
        if (isset($where_field) && isset($where_value)) {
            $query .= " WHERE ";
            $i=0;
            foreach($where_field as $arr) {
                if ($i>0) {
                    $query .= sprintf(" %s `%s`='%s'",mysql_escape_string($opr[$i-1]),
                                                mysql_escape_string($where_field[$i]),
                                                mysql_escape_string($where_value[$i]));
                } else {
                    $query .= sprintf("`%s`='%s'", mysql_escape_string($where_field[$i]),
                                                mysql_escape_string($where_value[$i]));
                }
                $i++;
            }
        }
       
        $this->script_log .= "Query: " . $query . "\n";
               
        $result = mysql_query($query) or die($this->mysql_error_report());
        $this->script_log .= "Query executed\n";
    }
   
    function testCall()
    {
        $this->query_result = Array();
        $this->CheckConnection();
        mysql_select_db('listy');
        mysql_query('CALL `listy_lastClubs`()')  or die($this->mysql_error_report());
    }
   
    function CallQuery($name){
        $this->query_result = Array();
        $this->CheckConnection();
       
        //mysql_query('USE listy');
        $query = sprintf("CALL `%s`()",mysql_escape_string($name));
        //$query = "CALL `listy_lastClubs`()";
       
        $result = mysql_query($query) or die($this->mysql_error_report());
        // or die("Cannot Query")
        $this->script_log .= "Query executed\n";
       
        //$this->query_result = mysql_fetch_array($result) or die("Cannot Featch Array.");

       
        $i=0;
        while($row = mysql_fetch_assoc($result)) {
            $this->query_result[$i] = $row;
            $i++;
        }
       
        $this->script_log .= "Array fetched \n";
       
        if ($i > 0) {
            $this->records_number = mysql_num_rows($result) or die($this->mysql_error_report());
            $this->script_log .= "Records Number setted to:" .$this->records_number . "\n";
        } else {
            $this->records_number = 0 ;
            $this->script_log .= "Records Number setted to:" .$this->records_number . "\n";
        }
       
        mysql_free_result($result);
       
        return $this->query_result;
    }
   
    function SelectQuery($table, $where_field=NULL, $where_value=NULL,
                            $opr=NULL, $DESC=true, $ORDER_BY="id") {
        $this->query_result = Array();
        // Example for useing class:
        // SelectQuery('links',Array('id','name'),Array(1,'garry'),Array('OR'));
        // Return: Array
        //
        // TODO IN THIS FUNCTION:
        // * ADD LIMIT AND START
        $this->CheckConnection();

       
        // BUILD SECURED QUERY - FOR SQL INJECTIONS PROTECTION
        $query = sprintf("SELECT * FROM `%s`",mysql_escape_string($table));
        if (isset($where_field[0])) {
            $query .= " WHERE ";
            $i=0;
            foreach($where_field as $arr) {
                if ($i>0) {
                    $query .= sprintf(" %s `%s`='%s'",mysql_escape_string($opr[$i-1]),
                                                mysql_escape_string($where_field[$i]),
                                                mysql_escape_string($where_value[$i]));
                } else {
                    $query .= sprintf("`%s`='%s'", mysql_escape_string($where_field[$i]),
                                                mysql_escape_string($where_value[$i]));
                }
                $i++;
            }
        }
           
        if ($DESC == 'true') {
            //$addon = " ORDER BY `id` DESC";
            $addon = sprintf(" ORDER BY `%s` DESC", $ORDER_BY);
        } else {
            //$addon = " ORDER BY `id`";
            $addon = sprintf(" ORDER BY `%s`", $ORDER_BY);
        }
        $query .= $addon;
        $this->script_log .= "Query: " . $query . "\n";
   
        $result = mysql_query($query) or die($this->mysql_error_report());
        // or die("Cannot Query")
        $this->script_log .= "Query executed\n";
       
        //$this->query_result = mysql_fetch_array($result) or die("Cannot Featch Array.");
       
        $i=0;
        while($row = mysql_fetch_assoc($result)) {
            $this->query_result[$i] = $row;
            $i++;
        }
       
       
        //$this->query_result = mysql_fetch_array($result);
        /*
        $i=0;
        foreach (mysql_fetch_assoc($result) as $row)
        {
            $this->query_result[$i] = $row;
            //array_push($this->query_result, $row);
            $i++;
        }
        */

       
        $this->script_log .= "Array fetched \n";
       
        if ($i > 0) {
            $this->records_number = mysql_num_rows($result) or die($this->mysql_error_report());
            $this->script_log .= "Records Number setted to:" .$this->records_number . "\n";
        } else {
            $this->records_number = 0 ;
            $this->script_log .= "Records Number setted to:" .$this->records_number . "\n";
        }
       
        mysql_free_result($result);
       
        return $this->query_result;
    }
   
    function CloseLink() {
        if ($this->mysql_link_status == true) {
            mysql_close($this->mysql_link) or die($this->mysql_error_report());
            $this->script_log .= "Mysql Link Closed\n";
            $this->mysql_link_status = false;
        } else {
            $this->script_log .= "Cannot close MySQL Link, the link dead\n";
        }
    }
   
   
   
    // SETTERS & GETTERS
   
    function getScriptLog() {
        return $this->script_log;
    }
   
    function getLastResult() {
        return $this->query_result;
    }
   
    function getLastRecordsNumber() {
        return $this->records_number;
    }
   
    function getDB() {
        return $this->mysql_database;
    }
   
    function setDB($database) {
        $this->mysql_database = $database;
        $this->script_log .= "New DB Setted: " . $this->mysql_database . "\n";
    }
   
    // PRIVATE FUNCTIONS
    function Connect() {
        $this->mysql_link = mysql_connect($this->mysql_host,
                                            $this->mysql_username,
                                            $this->mysql_password, 0, 65536) or die($this->mysql_error_report());
        $this->script_log .= "Conncted\n";
       
        mysql_select_db($this->mysql_database) or die($this->mysql_error_report());
        $this->script_log .= "Selected db: " . $this->mysql_database . "\n";
        $this->mysql_link_status=true;
    }
   
    function CheckConnection() {
        if ($this->mysql_link == NULL || $this->mysql_link_status == false) {
            $this->Connect();
        }  
        mysql_query("set character set 'utf8'");
    }

    function mysql_error_report() {
        echo mysql_error();
    }
   
       
}
?>

Demo of use:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?
require_once('./mysql.class.php');
var $inst;
$inst = new MySQL();
$inst->Connect();

$arr = $inst->SelectQuery('links',Array('url','name'),
                            Array('http://www.garry-lachman.com','Garry Lachman'),
                            Array(' AND '));
                           
$arr = $inst->SelectQuery('links');
echo "<b>Record:" . $arr[0]['name'] . "</b><br/>";
echo "<b>Num Records:" . $inst->getLastRecordsNumber(). "</b>";

$inst->UpdateQuery('links',Array('name'),Array('garry'),Array('id'),Array(555));
$inst->InsertQuery('links',Array('name','url'),Array('dfrfjfd','http://ajavdcvc'));

$inst->CloseLink();

echo '<h2>Script Log:</h2>';
?>

Have a fun ;)
Garry Lachman

Share

mySQL to JSON PHP Class

Written by Garry Lachman (Admin). Filed under PHP + mySQL. Tagged , , , , , . .

Hi,
A little class the i found here.
The class is very useful to generate json from mySQL result object.

The class:

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
class mysql2json{
     static public function getJSON($resultSet,$affectedRecords){
        mb_internal_encoding("UTF-8");
         $numberRows=0;
         $arrfieldName=array();
         $i=0;
         $json="";
        //print("Test");
         while ($i < mysql_num_fields($resultSet))  {
             $meta = mysql_fetch_field($resultSet, $i);
            if (!$meta) {
            }else{
            $arrfieldName[$i]=$meta->name;
            }
            $i++;
         }
         $i=0;
          $json="{\n\"data\": [\n";
        while($row=mysql_fetch_array($resultSet, MYSQL_NUM)) {
            $i++;
            //print("Ind ".$i."-$affectedRecords<br>");
            $json.="{\n";
            for($r=0;$r < count($arrfieldName);$r++) {
                $json.="\"$arrfieldName[$r]\" :    \"$row[$r]\"";
                if($r < count($arrfieldName)-1){
                    $json.=",\n";
                }else{
                    $json.="\n";
                }
            }
             
             if($i!=$affectedRecords){
                 $json.="\n},\n";
             }else{
                 $json.="\n}\n";
             }
             
        }
        $json.="]\n};";  
            return $json;
     }
}

Usage:

1
2
3
4
5
6
7
8
require_once("mysql2json.class.php");
mb_internal_encoding("UTF-8");

$result = mysql_query("select * from users");
$count=mysql_affected_rows();

$objJSON=new mysql2json();
print(trim($objJSON->getJSON($result,$count)));

Have a nice day,
Garry Lachman

Share

Migrating from PHP 4 to PHP 5 Presentation

Written by Garry Lachman (Admin). Filed under PHP + mySQL. Tagged , , , , . .

Migrating from PHP 4 to PHP 5 by Derick Rethans.
Really good one, just give a look…

http://talks.php.net/show/migrating-lt2005

Have Fun ;)
Garry Lachman

Share

PHP MySQL Shopping Cart Tutorial in PHP

Written by Garry Lachman (Admin). Filed under PHP + mySQL. Tagged , , , , , , , , , , , , . .

Very good & useful tutorial that i found while search the web about
Abstracting of shopping cart….

“Yes, this is a another shopping cart tutorial. I am planning to make this tutorial to cover a more sophisticated shopping cart solution but for now it only explains a basic shopping cart. I will improve it in time so stay tuned.”

Check if out here: http://www.phpwebcommerce.com/

Have fun,
Garry Lachman

UF4W22PSSX9C

Share

Factory Design Pattern in PHP5

Written by Garry Lachman (Admin). Filed under PHP + mySQL. Tagged , , , , , , . .

Factory Method return you the specific object by params he gets.
Lets make an example… we got 2 different classes for students that extends StudentAbstract class,
now we can make factory class that return the class by param.

StudentAbstract.php

1
2
3
4
abstract class StudentAbstract {
    abstract function getFirstName();
    abstract function getLastName();
}

FirstGradeStudent.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
include_once('StudentAbstract.php');

class FirstGradeStudent extends StudentAbstract {
    private $firstName;
    private $lastName;

    private function __construct() {
        $this->firstName = "Garry";
        $this->lastName = "Lachman";
    }

    public function getFirstName()  {
        return $this->firstName;
    }

    public function getLastName()   {
        return $this->lastName;
    }
}

SecondGradeStudent.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
include_once('StudentAbstract.php');

class SecondGradeStudent extends StudentAbstract    {
    private $firstName;
    private $lastName;

    private function __construct() {
        $this->firstName = "Polani";
        $this->lastName = "Almoni";
    }

    public function getFirstName()  {
        return $this->firstName;
    }

    public function getLastName()   {
        return $this->lastName;
    }
}

GetStudentFactory.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
include_once("FirstGradeStudent.php");
include_once("SecondGradeStudent.php");

class GetStudentFactory {
    public function getStudent($grade)  {
        $student = NULL;
        switch ($grade) {
            case "first":
                $student = new FirstGradeStudent();
            break;

            case "second";
                $student = new SecondGradeStudent();
            break;

            default:
                $student = new FirstGradeStudent();
            break;
        }
        return $student;
    }
}

Test.php

1
2
3
4
5
6
7
8
9
include_once("GetStudentFactory.php");

$factory = new GetStudentFactory();

$firstGrade = $factory->getStudent("first");
// return FirstGradeStudent class

$secondGrade = $factory->getStudent("second");
// return SecondGradeStudent class

Have Fun ;)
Garry Lachman

Share

Doru Moisa’s Blog: Static call versus Singleton call in PHP

Written by Garry Lachman (Admin). Filed under PHP + mySQL. Tagged , , , , , . .

New blog post by Doru Moisa about Static call vs. Singleton… very recommended!!!

“In the past several months I’ve been working with a rather large application built with symfony. I noticed that symfony makes heavy use of the Singleton pattern (other frameworks, like Zend do that too)…”

http://moisadoru.wordpress.com/2010/03/02/static-call-versus-singleton-call-in-php/

Enjoy ;)
Garry Lachman

Share

Adapter Design Pattern in PHP5

Written by Garry Lachman (Admin). Filed under PHP + mySQL. Tagged , , , . .

Adapter patter is very simply pattern that make an interface
for another class using his functions

ExampleItem.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
class ExampleItem   {
    private $name;
    private $title;

    private fucntion __construct($name, $title) {
        $this->name = $name;
        $this->title = $title;
    }

    public function getName()   {
        return $this->name;
    }

    public function getTitle()  {
        return $this->title;
    }
}
?>

ExampleItemAdapter.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
include("ExampleItem.php");

class ExampleItemAdapter    {
    private $exampleItem;

    private fucntion __construct(ExampleItem $exampleItem)  {
        $this->exampleItem = $exampleItem;
    }

    public function getItemInfo()   {
        return $this->exampleItem->getName() . " - " . $this->exampleItem->getTitle();
    }
}
?>

testAdapter.php

1
2
3
4
5
6
7
8
9
<?php
include("ExampleItem.php");
include("ExampleItemAdapter.php");

$test = new ExampleItemAdapter(new ExampleItem("Garry Lachman","SomeTitle"));

echo $test->getItemInfo();
// result: "Garry Lachman - SomeTitle"
?>

Have Fun ;)
Garry Lachman

Share

“ereg is deprecated” warnings in PHP 5.3

Written by Garry Lachman (Admin). Filed under PHP + mySQL. Tagged , , , , , , , , , , , . .

If you try to install systems like OSCommerce on PHP 5.3.x you may got strange
error like “ereg is deprecated…”.

Here is the solution!!!

1
ereg('RegExp', $x $y);

becomes

1
preg_match('/RegExp/', $x $y);

dont forget “/ /” between the regexp code!!!

Same for “ereg_replace”

1
ereg_replace('RegExp', $x, $y);

becomes

1
preg_replace('/RegExp/', $x, $y);

Thanks,
Garry Lachman

Share