├── .gitattributes
├── .gitignore
├── Database.php
├── README.md
├── config.php
├── db.sql
└── sample.php
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
4 | # Custom for Visual Studio
5 | *.cs diff=csharp
6 | *.sln merge=union
7 | *.csproj merge=union
8 | *.vbproj merge=union
9 | *.fsproj merge=union
10 | *.dbproj merge=union
11 |
12 | # Standard to msysgit
13 | *.doc diff=astextplain
14 | *.DOC diff=astextplain
15 | *.docx diff=astextplain
16 | *.DOCX diff=astextplain
17 | *.dot diff=astextplain
18 | *.DOT diff=astextplain
19 | *.pdf diff=astextplain
20 | *.PDF diff=astextplain
21 | *.rtf diff=astextplain
22 | *.RTF diff=astextplain
23 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | #################
2 | ## Eclipse
3 | #################
4 |
5 | *.pydevproject
6 | .project
7 | .metadata
8 | bin/
9 | tmp/
10 | *.tmp
11 | *.bak
12 | *.swp
13 | *~.nib
14 | local.properties
15 | .classpath
16 | .settings/
17 | .loadpath
18 |
19 | # External tool builders
20 | .externalToolBuilders/
21 |
22 | # Locally stored "Eclipse launch configurations"
23 | *.launch
24 |
25 | # CDT-specific
26 | .cproject
27 |
28 | # PDT-specific
29 | .buildpath
30 |
31 |
32 | #################
33 | ## Visual Studio
34 | #################
35 |
36 | ## Ignore Visual Studio temporary files, build results, and
37 | ## files generated by popular Visual Studio add-ons.
38 |
39 | # User-specific files
40 | *.suo
41 | *.user
42 | *.sln.docstates
43 |
44 | # Build results
45 |
46 | [Dd]ebug/
47 | [Rr]elease/
48 | x64/
49 | build/
50 | [Bb]in/
51 | [Oo]bj/
52 |
53 | # MSTest test Results
54 | [Tt]est[Rr]esult*/
55 | [Bb]uild[Ll]og.*
56 |
57 | *_i.c
58 | *_p.c
59 | *.ilk
60 | *.meta
61 | *.obj
62 | *.pch
63 | *.pdb
64 | *.pgc
65 | *.pgd
66 | *.rsp
67 | *.sbr
68 | *.tlb
69 | *.tli
70 | *.tlh
71 | *.tmp
72 | *.tmp_proj
73 | *.log
74 | *.vspscc
75 | *.vssscc
76 | .builds
77 | *.pidb
78 | *.log
79 | *.scc
80 |
81 | # Visual C++ cache files
82 | ipch/
83 | *.aps
84 | *.ncb
85 | *.opensdf
86 | *.sdf
87 | *.cachefile
88 |
89 | # Visual Studio profiler
90 | *.psess
91 | *.vsp
92 | *.vspx
93 |
94 | # Guidance Automation Toolkit
95 | *.gpState
96 |
97 | # ReSharper is a .NET coding add-in
98 | _ReSharper*/
99 | *.[Rr]e[Ss]harper
100 |
101 | # TeamCity is a build add-in
102 | _TeamCity*
103 |
104 | # DotCover is a Code Coverage Tool
105 | *.dotCover
106 |
107 | # NCrunch
108 | *.ncrunch*
109 | .*crunch*.local.xml
110 |
111 | # Installshield output folder
112 | [Ee]xpress/
113 |
114 | # DocProject is a documentation generator add-in
115 | DocProject/buildhelp/
116 | DocProject/Help/*.HxT
117 | DocProject/Help/*.HxC
118 | DocProject/Help/*.hhc
119 | DocProject/Help/*.hhk
120 | DocProject/Help/*.hhp
121 | DocProject/Help/Html2
122 | DocProject/Help/html
123 |
124 | # Click-Once directory
125 | publish/
126 |
127 | # Publish Web Output
128 | *.Publish.xml
129 | *.pubxml
130 |
131 | # NuGet Packages Directory
132 | ## TODO: If you have NuGet Package Restore enabled, uncomment the next line
133 | #packages/
134 |
135 | # Windows Azure Build Output
136 | csx
137 | *.build.csdef
138 |
139 | # Windows Store app package directory
140 | AppPackages/
141 |
142 | # Others
143 | sql/
144 | *.Cache
145 | ClientBin/
146 | [Ss]tyle[Cc]op.*
147 | ~$*
148 | *~
149 | *.dbmdl
150 | *.[Pp]ublish.xml
151 | *.pfx
152 | *.publishsettings
153 |
154 | # RIA/Silverlight projects
155 | Generated_Code/
156 |
157 | # Backup & report files from converting an old project file to a newer
158 | # Visual Studio version. Backup files are not needed, because we have git ;-)
159 | _UpgradeReport_Files/
160 | Backup*/
161 | UpgradeLog*.XML
162 | UpgradeLog*.htm
163 |
164 | # SQL Server files
165 | App_Data/*.mdf
166 | App_Data/*.ldf
167 |
168 | #############
169 | ## Windows detritus
170 | #############
171 |
172 | # Windows image file caches
173 | Thumbs.db
174 | ehthumbs.db
175 |
176 | # Folder config file
177 | Desktop.ini
178 |
179 | # Recycle Bin used on file shares
180 | $RECYCLE.BIN/
181 |
182 | # Mac crap
183 | .DS_Store
184 |
185 |
186 | #############
187 | ## Python
188 | #############
189 |
190 | *.py[co]
191 |
192 | # Packages
193 | *.egg
194 | *.egg-info
195 | dist/
196 | build/
197 | eggs/
198 | parts/
199 | var/
200 | sdist/
201 | develop-eggs/
202 | .installed.cfg
203 |
204 | # Installer logs
205 | pip-log.txt
206 |
207 | # Unit test / coverage reports
208 | .coverage
209 | .tox
210 |
211 | #Translations
212 | *.mo
213 |
214 | #Mr Developer
215 | .mr.developer.cfg
216 |
--------------------------------------------------------------------------------
/Database.php:
--------------------------------------------------------------------------------
1 |
6 | * @copyright june 2013
7 | */
8 | class Database
9 | {
10 |
11 | protected $pdo;
12 | private $datasec = array();
13 | private $ctrl_dir = array();
14 | private $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
15 | private $old_offset = 0;
16 | private $error_message = '';
17 | public $is_transaction = 0;
18 | private $data_exist;
19 |
20 | public function __construct($hostname, $port_number, $username_db, $password_db, $db_name)
21 | {
22 | try {
23 | $this->pdo = new PDO("mysql:host=" . $hostname . ";dbname=" . $db_name . ";port=" . $port_number, $username_db, $password_db);
24 | $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
25 | $this->pdo->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''))");
26 |
27 | }
28 | catch (PDOException $e) {
29 | echo "error " . $e->getMessage();
30 | }
31 | }
32 |
33 | /**
34 | * custom query , joining multiple table, aritmathic etc
35 | *
36 | * @param string $sql custom query
37 | * @param array $data associative array
38 | * @return array recordset
39 | */
40 | public function query($sql, $data = null)
41 | {
42 | if ($data !== null) {
43 | $dat = array_values($data);
44 | }
45 | $sel = $this->pdo->prepare($sql);
46 |
47 | try {
48 | if ($data !== null) {
49 | $sel->execute($dat);
50 | } else {
51 | $sel->execute();
52 | }
53 | $sel->setFetchMode(PDO::FETCH_OBJ);
54 | return $sel;
55 | }
56 | catch (PDOException $exception) {
57 | $this->setErrorMessage($exception->getMessage());
58 | echo $this->getErrorMessage();
59 | exit();
60 | }
61 |
62 | }
63 |
64 | /**
65 | * begin a transaction.
66 | */
67 | public function begin_transaction()
68 | {
69 | $this->pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, 0);
70 | $this->pdo->beginTransaction();
71 | }
72 | /**
73 | * commit the transaction.
74 | */
75 | public function commit()
76 | {
77 | $this->pdo->commit();
78 | $this->pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, 1);
79 | }
80 | /**
81 | * rollback the transaction.
82 | */
83 | public function rollback()
84 | {
85 | $this->pdo->rollBack();
86 | $this->pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, 1);
87 | }
88 |
89 | /**
90 | * [getErrorMessage return string throw exception
91 | *
92 | * @return string return string error
93 | */
94 | function getErrorMessage()
95 | {
96 | return $this->error_message;
97 | }
98 |
99 | /**
100 | * [setErrorMessage set error message]
101 | *
102 | * @param [type] $error [description]
103 | */
104 | function setErrorMessage($error)
105 | {
106 | $this->error_message = $error;
107 | }
108 |
109 | /**
110 | * fetch only one row
111 | *
112 | * @param string $table table name
113 | * @param string $col condition column
114 | * @param string $val value column
115 | * @return array recordset
116 | */
117 | public function fetchSingleRow($table, $col, $val)
118 | {
119 | $nilai = array(
120 | $val
121 | );
122 | $sel = $this->pdo->prepare("SELECT * FROM $table WHERE $col=?");
123 | try {
124 | $sel->execute($nilai);
125 | $sel->setFetchMode(PDO::FETCH_OBJ);
126 | $obj = $sel->fetch();
127 | return $obj;
128 | }
129 | catch (PDOException $exception) {
130 | $this->setErrorMessage($exception->getMessage());
131 | echo $this->getErrorMessage();
132 | }
133 | }
134 |
135 | public function fetchCustomSingle($sql, $data = null)
136 | {
137 | if ($data !== null) {
138 | $dat = array_values($data);
139 | }
140 | $sel = $this->pdo->prepare($sql);
141 | try {
142 | if ($data !== null) {
143 | $sel->execute($dat);
144 | } else {
145 | $sel->execute();
146 | }
147 | $sel->setFetchMode(PDO::FETCH_OBJ);
148 | $obj = $sel->fetch();
149 | return $obj;
150 | }
151 | catch (PDOException $exception) {
152 | $this->setErrorMessage($exception->getMessage());
153 | echo $this->getErrorMessage();
154 | }
155 | }
156 |
157 | /**
158 | * fetch all data
159 | *
160 | * @param string $table table name
161 | * @return array recordset
162 | */
163 | public function fetchAll($table)
164 | {
165 | $sel = $this->pdo->prepare("SELECT * FROM $table");
166 | try {
167 | $sel->execute();
168 | $sel->setFetchMode(PDO::FETCH_OBJ);
169 | return $sel;
170 | }
171 | catch (PDOException $exception) {
172 | $this->setErrorMessage($exception->getMessage());
173 | echo $this->getErrorMessage();
174 | }
175 | }
176 |
177 | /**
178 | * check if there is exist data
179 | *
180 | * @param string $table table name
181 | * @param array $dat array list of data to find
182 | * @return true or false
183 | */
184 | public function checkExist($table, $dat)
185 | {
186 |
187 | $data = array_values($dat);
188 | //grab keys
189 | $cols = array_keys($dat);
190 | $col = implode(', ', $cols);
191 |
192 | foreach ($cols as $key) {
193 | $keys = $key . "=?";
194 | $mark[] = $keys;
195 | }
196 |
197 | $count = count($dat);
198 | if ($count > 1) {
199 | $im = implode(' and ', $mark);
200 | $sel = $this->pdo->prepare("SELECT * from $table WHERE $im");
201 | } else {
202 | $im = implode('', $mark);
203 | $sel = $this->pdo->prepare("SELECT * from $table WHERE $im");
204 | }
205 | $sel->execute($data);
206 | $sel->setFetchMode(PDO::FETCH_OBJ);
207 | $count = $sel->rowCount();
208 | if ($count > 0) {
209 | $obj = $sel->fetch();
210 | $this->data_exist = $obj;
211 | return $this;
212 | } else {
213 | return false;
214 | }
215 | }
216 |
217 | /**
218 | * return data from checkExist function
219 | *
220 | * @return [type] [description]
221 | */
222 | public function getData()
223 | {
224 | return $this->data_exist;
225 | }
226 |
227 | /**
228 | * search data
229 | *
230 | * @param string $table table name
231 | * @param array $col column name
232 | * @param array $where where condition
233 | * @return array recordset
234 | */
235 | public function search($table, $col, $where)
236 | {
237 | $data = array_values($where);
238 | foreach ($data as $key) {
239 | $val = '%' . $key . '%';
240 | $value[] = $val;
241 | }
242 | //grab keys
243 | $cols = array_keys($where);
244 | $colum = implode(', ', $col);
245 |
246 | foreach ($cols as $key) {
247 | $keys = $key . " LIKE ?";
248 | $mark[] = $keys;
249 | }
250 | $count = count($where);
251 | if ($count > 1) {
252 | $im = implode(' OR ', $mark);
253 | $sel = $this->pdo->prepare("SELECT * from $table WHERE $im");
254 | } else {
255 | $im = implode('', $mark);
256 | $sel = $this->pdo->prepare("SELECT * from $table WHERE $im");
257 | }
258 |
259 | $sel->execute($value);
260 | $sel->setFetchMode(PDO::FETCH_OBJ);
261 | return $sel;
262 | }
263 | /**
264 | * insert data to table
265 | *
266 | * @param string $table table name
267 | * @param array $dat associative array 'column_name'=>'val'
268 | */
269 | public function insert($table, $dat)
270 | {
271 |
272 | if ($dat !== null) {
273 | $data = array_values($dat);
274 | }
275 | //grab keys
276 | $cols = array_keys($dat);
277 | $col = implode(', ', $cols);
278 |
279 | //grab values and change it value
280 | $mark = array();
281 | foreach ($data as $key) {
282 | $keys = '?';
283 | $mark[] = $keys;
284 | }
285 | $im = implode(', ', $mark);
286 | $ins = $this->pdo->prepare("INSERT INTO $table ($col) values ($im)");
287 | try {
288 | $ins->execute($data);
289 | return true;
290 | }
291 | catch (PDOException $exception) {
292 | $this->setErrorMessage($exception->getMessage());
293 | return false;
294 | }
295 | }
296 |
297 | /**
298 | * updateMulti mapper array
299 | * @param array $update_value array recordset
300 | * @param array $primary_key_value primary key value recordset
301 | * @return array array recordset
302 | */
303 | public function mapper($update_value,$primary_key_value) {
304 | $index=0;
305 | foreach ($update_value as $value) {
306 | $primary_value = $primary_key_value[$index];
307 | $append[] = array_map(function ($str) use($primary_value) { return "WHEN '".$primary_value."' THEN '$str'"; }, $value);
308 | $index++;
309 | }
310 | return $append;
311 | }
312 |
313 | /**
314 | * [updateMulti update bulk sql]
315 | * @param [string] $table_name table name
316 | * @param array $update_value array recordset with key value column_name and value of record
317 | * @param string $primary_key_name primary key column_name
318 | * @param array $primary_key_value primary key value (single array )
319 | * @return boolean update query
320 | */
321 |
322 | public function updateMulti($table_name,$update_value,$primary_key_name,$primary_key_value) {
323 |
324 | $data_mapper_update = $this->mapper($update_value,$primary_key_value);
325 | $data_mapper = array_keys($data_mapper_update[0]);
326 |
327 | $collection = [];
328 |
329 | foreach ($data_mapper as $key) {
330 | $collection[] = "$key = (CASE $primary_key_name ".implode(' ', array_unique(
331 | // `array_column` will give you all values under `$key`
332 | array_column($data_mapper_update, $key)
333 | ))." END)";
334 | }
335 | $primary_key_quote = sprintf("'%s'", implode("','", $primary_key_value ) );
336 | $query = "UPDATE $table_name SET ".implode(",", $collection)." WHERE $primary_key_name IN ($primary_key_quote)";
337 | $ins = $this->pdo->prepare($query);
338 | try {
339 | $ins->execute();
340 | return true;
341 | }
342 | catch (PDOException $exception) {
343 | $this->setErrorMessage($exception->getMessage());
344 | return false;
345 | }
346 | }
347 |
348 | /**
349 | * insert multiple row at once
350 | *
351 | * @param [type] $table table name
352 | * @param [type] $array_data multi array
353 | * @return [type] boolen
354 | */
355 | public function insertMulti($table_name, $values)
356 | {
357 | $column_name = array_keys($values[0]);
358 | $column_name = implode(',', $column_name);
359 |
360 | $value_data = array();
361 | foreach ($values as $data => $val) {
362 |
363 | $value_data[] = '("' . implode('","', array_values($val)) . '")';
364 | }
365 | $string_value = implode(",", $value_data);
366 |
367 | $sql = "INSERT INTO $table_name ($column_name) VALUES " . $string_value;
368 | $ins = $this->pdo->prepare($sql);
369 | try {
370 | $ins->execute();
371 | return true;
372 | }
373 | catch (PDOException $exception) {
374 | $this->setErrorMessage($exception->getMessage());
375 | return false;
376 | }
377 | }
378 |
379 |
380 | public function getLastInsertId()
381 | {
382 | return $this->pdo->lastInsertId();
383 | }
384 |
385 |
386 | /**
387 | * update record
388 | *
389 | * @param string $table table name
390 | * @param array $dat associative array 'col'=>'val'
391 | * @param string $id primary key column name
392 | * @param int $val key value
393 | */
394 | public function update($table, $dat, $id, $val)
395 | {
396 | if ($dat !== null) {
397 | $data = array_values($dat);
398 | }
399 | array_push($data, $val);
400 | //grab keys
401 | $cols = array_keys($dat);
402 | $mark = array();
403 | foreach ($cols as $col) {
404 | $mark[] = $col . "=?";
405 | }
406 | $im = implode(', ', $mark);
407 | $ins = $this->pdo->prepare("UPDATE $table SET $im where $id=?");
408 | try {
409 | $ins->execute($data);
410 | return true;
411 | }
412 | catch (PDOException $exception) {
413 | $this->setErrorMessage($exception->getMessage());
414 | return false;
415 | }
416 |
417 | }
418 |
419 | /**
420 | * delete record
421 | *
422 | * @param string $table table name
423 | * @param string $where column name for condition (commonly primay key column name)
424 | * @param int $id key value
425 | */
426 | public function delete($table, $where, $id)
427 | {
428 | $data = array(
429 | $id
430 | );
431 | $sel = $this->pdo->prepare("Delete from $table where $where=?");
432 | try {
433 | $sel->execute($data);
434 | return true;
435 | }
436 | catch (PDOException $exception) {
437 | $this->setErrorMessage($exception->getMessage());
438 | return false;
439 | }
440 | }
441 |
442 |
443 | //write file
444 | function createFile($file, $isi)
445 | {
446 | $fp = fopen($file, 'w');
447 | if (!$fp) {
448 | return 0;
449 | }
450 | fwrite($fp, $isi);
451 | fclose($fp);
452 | return 1;
453 |
454 | }
455 | //hapus directory
456 | function deleteDirectory($dir)
457 | {
458 | if (!file_exists($dir)) {
459 | return true;
460 | }
461 | if (!is_dir($dir) || is_link($dir)) {
462 | return unlink($dir);
463 | }
464 | foreach (scandir($dir) as $item) {
465 | if ($item == '.' || $item == '..') {
466 | continue;
467 | }
468 | if (!$this->deleteDirectory($dir . "/" . $item)) {
469 | chmod($dir . "/" . $item, 0777);
470 | if (!$this->deleteDirectory($dir . "/" . $item)) {
471 | return false;
472 | }
473 | }
474 | ;
475 | }
476 | return rmdir($dir);
477 | }
478 |
479 |
480 |
481 | //selected active menu
482 | public function terpilih($nav, $group_id)
483 | {
484 | $pilih = "";
485 | // $mod = $this->fetchSingleRow('sys_menu','nav_act',$nav);
486 | if ($nav != '') {
487 | $menu = $this->query(
488 | "select * from sys_menu where url=?", array(
489 | 'url' => $nav
490 | )
491 | );
492 |
493 | foreach ($menu as $men) {
494 |
495 | $id_group[] = $group_id;
496 | if ($men->parent != 0) {
497 | $data = $this->fetchSingleRow('sys_menu', 'id', $men->parent);
498 |
499 |
500 | if ($group_id == $men->parent || $data->parent == $group_id) {
501 |
502 |
503 |
504 | $pilih = 'active';
505 | } else {
506 | $pilih = "";
507 | }
508 |
509 | } else {
510 | $data = $this->fetchSingleRow('sys_menu', 'id', $men->parent);
511 |
512 |
513 | if ($group_id == $men->parent) {
514 |
515 |
516 | $pilih = 'active';
517 | } else {
518 | $pilih = "";
519 | }
520 | }
521 |
522 |
523 |
524 | }
525 | }
526 |
527 |
528 |
529 | return $pilih;
530 | }
531 | // Menu builder function, parentId 0 is the root
532 | function buildMenu($url, $parent, $menu)
533 | {
534 | $html = "";
535 | if (isset($menu['parents'][$parent])) {
536 | foreach ($menu['parents'][$parent] as $itemId) {
537 |
538 | if (!isset($menu['parents'][$itemId])) {
539 | if ($menu['items'][$itemId]['type_menu'] == 'separator') {
540 | $html .= "
";
541 | } else {
542 | $html .= "";
546 | if ($menu['items'][$itemId]['icon'] != '') {
547 | $html .= "";
548 | } else {
549 | $html .= "";
550 | }
551 | $html .= ucwords($menu['items'][$itemId]['page_name']) . "";
552 | }
553 |
554 | }
555 |
556 | if (isset($menu['parents'][$itemId])) {
557 |
558 |
559 |
560 | $html .= "";
574 | }
575 | }
576 |
577 | }
578 | return $html;
579 | }
580 |
581 | public function createMenu()
582 | {
583 | // Select all entries from the menu table
584 | $result=$this->query(
585 | "select sys_menu.*,sys_menu_role.read_act,sys_menu_role.insert_act,sys_menu_role.update_act,sys_menu_role.delete_act,sys_menu_role.group_level from sys_menu
586 | left join sys_menu_role on sys_menu.id=sys_menu_role.id_menu
587 | where sys_menu_role.group_level=? and sys_menu_role.read_act=? and tampil=? and hide=? ORDER BY parent, urutan_menu asc",
588 | array(
589 | 'sys_menu_role.group_level'=>$_SESSION['group_level'],
590 | 'sys_menu_role.read_act'=>'Y',
591 | 'tampil'=>'Y',
592 | 'hide' => 'N'
593 | )
594 | );
595 |
596 |
597 | // Create a multidimensional array to list items and parents
598 | $menu = array(
599 | 'items' => array(),
600 | 'parents' => array()
601 | );
602 | // Builds the array lists with data from the menu table
603 | foreach ($result as $items) {
604 |
605 | $items = $this->converObjToArray($items);
606 |
607 | // Creates entry into items array with current menu item id ie.
608 | $menu['items'][$items['id']] = $items;
609 | // Creates entry into parents array. Parents array contains a list of all items with children
610 | $menu['parents'][$items['parent']][] = $items['id'];
611 | }
612 | return $this->buildMenu(uri_segment(0), 0, $menu);
613 | }
614 |
615 | //obj to array
616 | function converObjToArray($obj)
617 | {
618 | if (is_object($obj)) {
619 | $obj = (array) $obj;
620 | }
621 | if (is_array($obj)) {
622 | $new = array();
623 | foreach ($obj as $key => $val) {
624 | $new[$key] = $this->converObjToArray($val);
625 | }
626 | } else {
627 | $new = $obj;
628 | }
629 |
630 | return $new;
631 | }
632 |
633 |
634 | //search function
635 | public function getRawWhereFilterForColumns($filter, $search_columns)
636 | {
637 | $filter = addslashes($filter);
638 | $search_terms = explode(' ', $filter);
639 | $search_condition = "";
640 |
641 | for ($i = 0; $i < count($search_terms); $i++) {
642 | $term = $search_terms[$i];
643 |
644 | for ($j = 0; $j < count($search_columns); $j++) {
645 | if ($j == 0) {
646 | $search_condition .= "(";
647 | }
648 | $search_field_name = $search_columns[$j];
649 | $search_condition .= "$search_field_name LIKE '%" . $term . "%'";
650 | if ($j + 1 < count($search_columns)) {
651 | $search_condition .= " OR ";
652 | }
653 | if ($j + 1 == count($search_columns)) {
654 | $search_condition .= ")";
655 | }
656 | }
657 | if ($i + 1 < count($search_terms)) {
658 | $search_condition .= " AND ";
659 | }
660 | }
661 | return $search_condition;
662 | }
663 |
664 |
665 | /**
666 | * upload image if image width more than 1200 then upload and compress to 1200, otherwise just upload it
667 | *
668 | * @param [type] $ext [description]
669 | * @param [type] $uploadedfile [description]
670 | * @param [type] $path [description]
671 | * @param [type] $actual_image_name [description]
672 | * @return [type] [description]
673 | */
674 | public function uploadImageCustom($ext, $uploadedfile, $path, $actual_image_name)
675 | {
676 | $image_size = getimagesize($uploadedfile);
677 | if ($image_size[0] >= 1200) {
678 | $this->compressImage($ext, $uploadedfile, $path, $actual_image_name, 1200);
679 | } else {
680 | $file = $uploadedfile;
681 | $path = $path . $actual_image_name;
682 | copy($uploadedfile, $path);
683 | }
684 |
685 | }
686 |
687 | public function uploadFile($uploadedfile, $path, $actual_image_name)
688 | {
689 | $file = $uploadedfile;
690 | $path = $path . $actual_image_name;
691 | copy($uploadedfile, $path);
692 | }
693 |
694 |
695 | function compressImage($ext, $uploadedfile, $path, $actual_image_name, $newwidth, $tinggi = null)
696 | {
697 |
698 |
699 |
700 | if ($ext == "image/jpeg" || $ext == "image/jpg") {
701 |
702 | $src = imagecreatefromjpeg($uploadedfile);
703 | } else if ($ext == "image/png") {
704 | $src = @imagecreatefrompng($uploadedfile);
705 | } else if ($ext == "image/gif") {
706 | $src = imagecreatefromgif($uploadedfile);
707 | } else {
708 |
709 | $src = imagecreatefrombmp($uploadedfile);
710 | }
711 |
712 | list($width, $height) = getimagesize($uploadedfile);
713 | if ($tinggi != null) {
714 | $newheight = $tinggi;
715 | } else {
716 | $newheight = ($height / $width) * $newwidth;
717 | }
718 |
719 | $tmp = imagecreatetruecolor($newwidth, $newheight);
720 | imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
721 | $filename = $path . $actual_image_name; //PixelSize_TimeStamp.jpg
722 | imagejpeg($tmp, $filename, 100);
723 | imagedestroy($tmp);
724 | return $filename;
725 | }
726 |
727 | function getDir($dir)
728 | {
729 | $modul_dir = explode(DIRECTORY_SEPARATOR, $dir);
730 | array_pop($modul_dir);
731 | array_pop($modul_dir);
732 |
733 | $modul_dir = implode(DIRECTORY_SEPARATOR, $modul_dir);
734 | return $modul_dir . DIRECTORY_SEPARATOR . "modul" . DIRECTORY_SEPARATOR;
735 | }
736 |
737 |
738 |
739 | /**
740 | * get uniqure name from filename
741 | *
742 | * @param string $file_name filename
743 | * @return string new unique filename
744 | */
745 | public function uniqueName($file_name)
746 | {
747 | $filename = $file_name;
748 | $filename = preg_replace("#[^a-z.0-9]#i", "", $filename);
749 | $ex = explode(".", $filename); // split filename
750 | $fileExt = end($ex); // ekstensi akhir
751 | $filename = time() . rand() . "." . $fileExt; //rename nama file';
752 | return $filename;
753 | }
754 |
755 | function addDir($name)
756 | {
757 | $name = str_replace("\\", "/", $name);
758 | $fr = "\x50\x4b\x03\x04";
759 | $fr .= "\x0a\x00";
760 | $fr .= "\x00\x00";
761 | $fr .= "\x00\x00";
762 | $fr .= "\x00\x00\x00\x00";
763 | $fr .= pack("V", 0);
764 | $fr .= pack("V", 0);
765 | $fr .= pack("V", 0);
766 | $fr .= pack("v", strlen($name));
767 | $fr .= pack("v", 0);
768 | $fr .= $name;
769 | /* $fr .= pack("V",$crc);
770 | $fr .= pack("V",$c_len);
771 | $fr .= pack("V",$unc_len);*/
772 | $this->datasec[] = $fr;
773 | $new_offset = strlen(implode("", $this->datasec));
774 | $cdrec = "\x50\x4b\x01\x02";
775 | $cdrec .= "\x00\x00";
776 | $cdrec .= "\x0a\x00";
777 | $cdrec .= "\x00\x00";
778 | $cdrec .= "\x00\x00";
779 | $cdrec .= "\x00\x00\x00\x00";
780 | $cdrec .= pack("V", 0);
781 | $cdrec .= pack("V", 0);
782 | $cdrec .= pack("V", 0);
783 | $cdrec .= pack("v", strlen($name));
784 | $cdrec .= pack("v", 0);
785 | $cdrec .= pack("v", 0);
786 | $cdrec .= pack("v", 0);
787 | $cdrec .= pack("v", 0);
788 | $ext = "\x00\x00\x10\x00";
789 | $ext = "\xff\xff\xff\xff";
790 | $cdrec .= pack("V", 16);
791 | $cdrec .= pack("V", $this->old_offset);
792 | $this->old_offset = $new_offset;
793 | $cdrec .= $name;
794 | $this->ctrl_dir[] = $cdrec;
795 | }
796 | function addFile($data, $name)
797 | {
798 | $name = str_replace("\\", "/", $name);
799 | $fr = "\x50\x4b\x03\x04";
800 | $fr .= "\x14\x00";
801 | $fr .= "\x00\x00";
802 | $fr .= "\x08\x00";
803 | $fr .= "\x00\x00\x00\x00";
804 | $unc_len = strlen($data);
805 | $crc = crc32($data);
806 | $zdata = gzcompress($data);
807 | $zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2);
808 | $c_len = strlen($zdata);
809 | $fr .= pack("V", $crc);
810 | $fr .= pack("V", $c_len);
811 | $fr .= pack("V", $unc_len);
812 | $fr .= pack("v", strlen($name));
813 | $fr .= pack("v", 0);
814 | $fr .= $name;
815 | $fr .= $zdata;
816 | $fr .= pack("V", $crc);
817 | $fr .= pack("V", $c_len);
818 | $fr .= pack("V", $unc_len);
819 | $this->datasec[] = $fr;
820 | $new_offset = strlen(implode("", $this->datasec));
821 | $cdrec = "\x50\x4b\x01\x02";
822 | $cdrec .= "\x00\x00";
823 | $cdrec .= "\x14\x00";
824 | $cdrec .= "\x00\x00";
825 | $cdrec .= "\x08\x00";
826 | $cdrec .= "\x00\x00\x00\x00";
827 | $cdrec .= pack("V", $crc);
828 | $cdrec .= pack("V", $c_len);
829 | $cdrec .= pack("V", $unc_len);
830 | $cdrec .= pack("v", strlen($name));
831 | $cdrec .= pack("v", 0);
832 | $cdrec .= pack("v", 0);
833 | $cdrec .= pack("v", 0);
834 | $cdrec .= pack("v", 0);
835 | $cdrec .= pack("V", 32);
836 | $cdrec .= pack("V", $this->old_offset);
837 | $this->old_offset = $new_offset;
838 | $cdrec .= $name;
839 | $this->ctrl_dir[] = $cdrec;
840 | }
841 | function file()
842 | {
843 | $data = implode("", $this->datasec);
844 | $ctrldir = implode("", $this->ctrl_dir);
845 | return $data . $ctrldir . $this->eof_ctrl_dir . pack("v", sizeof($this->ctrl_dir)) . pack("v", sizeof($this->ctrl_dir)) . pack("V", strlen($ctrldir)) . pack("V", strlen($data)) . "\x00\x00";
846 | }
847 |
848 | function getFilesFromFolder($directory, $put_into)
849 | {
850 | $sp = DIRECTORY_SEPARATOR;
851 | if ($handle = opendir($directory)) {
852 | while (false !== ($file = readdir($handle))) {
853 | if (is_file($directory . $file)) {
854 | $fileContents = file_get_contents($directory . $file);
855 | $this->addFile($fileContents, $put_into . $file);
856 | } elseif ($file != '.' && $file != '..' && is_dir($directory . $file)) {
857 | $this->addDir($put_into . $file . $sp);
858 | $this->getFilesFromFolder($directory . $file . $sp, $put_into . $file . $sp);
859 | }
860 | }
861 | }
862 | closedir($handle);
863 | }
864 | function downloadfolder($fd, $str_data, $put_into)
865 | {
866 | $this->getFilesFromFolder($fd, $put_into . '/');
867 | $this->addFile($str_data, "write.php");
868 | header("Content-Disposition: attachment; filename=" . $this->cs(basename($fd)) . ".zip");
869 | header("Content-Type: application/zip");
870 | header("Content-Length: " . strlen($this->file()));
871 | flush();
872 | echo $this->file();
873 | exit();
874 | }
875 |
876 |
877 | function getDirExcel($dir)
878 | {
879 | $modul_dir = explode(DIRECTORY_SEPARATOR, $dir);
880 | array_pop($modul_dir);
881 | array_pop($modul_dir);
882 |
883 | $modul_dir = implode(DIRECTORY_SEPARATOR, $modul_dir);
884 | return $modul_dir . DIRECTORY_SEPARATOR . "modul" . DIRECTORY_SEPARATOR . "excel" . DIRECTORY_SEPARATOR . 'result' . DIRECTORY_SEPARATOR;
885 | }
886 |
887 | function downloadfolderExcel($fd, $str_data, $put_into)
888 | {
889 | $this->getFilesFromFolder($fd, 'template/');
890 | foreach ($str_data as $str => $value) {
891 | $this->addFile($str, $value);
892 |
893 | }
894 |
895 | header("Content-Disposition: attachment; filename=" . $this->cs(basename($put_into)) . ".zip");
896 | header("Content-Type: application/zip");
897 | header("Content-Length: " . strlen($this->file()));
898 | flush();
899 | echo $this->file();
900 | unlink($fd . $put_into . '.xlsx');
901 | exit();
902 | }
903 | function cs($t)
904 | {
905 | return str_replace(" ", "_", $t);
906 | }
907 |
908 | public function urlAccess($url)
909 | {
910 | $check_access = $this->fetchCustomSingle(
911 | "select sys_menu.url from sys_menu inner join sys_menu_role on sys_menu.id=sys_menu_role.id_menu
912 | where sys_menu_role.group_level=? and sys_menu_role.read_act=?", array(
913 | 'group_level' => $_SESSION['group_level'],
914 | 'read_act' => 'Y',
915 | 'url' => $url
916 | )
917 | );
918 | if ($check_access) {
919 | return true;
920 | } else {
921 | return false;
922 | }
923 | }
924 |
925 | /**
926 | * what can user do, if you call this function from modal, you have to prepare $url param
927 | *
928 | * @param [type] $role_act
929 | * @param string $url
930 | * @return void
931 | */
932 | public function userCan($role_act,$url="")
933 | {
934 |
935 | $array_act = array(
936 | 'read' => 'read_act',
937 | 'insert' => 'insert_act',
938 | 'update' => 'update_act',
939 | 'delete' => 'delete_act',
940 | 'import' => 'import_act'
941 | );
942 | if($url!="") {
943 | $url = $url;
944 | } else {
945 | $url = uri_segment(0);
946 | }
947 |
948 | $check_access = $this->fetchCustomSingle(
949 | "select read_act,insert_act,update_act,delete_act,sys_menu.url from sys_menu inner join sys_menu_role on sys_menu.id=sys_menu_role.id_menu
950 | where hide='N' and sys_menu_role.group_level=? and $array_act[$role_act]=? and url=?", array(
951 | 'group_level' => $_SESSION['group_level'],
952 | "$array_act[$role_act]" => 'Y',
953 | 'url' => $url
954 | )
955 | );
956 | if ($check_access) {
957 | return true;
958 | } else {
959 | return false;
960 | }
961 | }
962 | public function roleUserMenu()
963 | {
964 | //simpan role url page user di array sesuai login session level
965 | $role_user=array();
966 | foreach ($this->query(
967 | "select sys_menu.url from sys_menu inner join sys_menu_role on sys_menu.id=sys_menu_role.id_menu
968 | where hide='N' and sys_menu_role.group_level=? and sys_menu_role.read_act=?", array('sys_menu_role.group_level'=>$_SESSION['group_level'],'sys_menu_role.read_act'=>'Y')
969 | ) as $role) {
970 | $role_user[]=$role->url;
971 | }
972 | return $role_user;
973 | }
974 |
975 | public function __destruct()
976 | {
977 | $this->pdo = null;
978 | }
979 | }
980 | ?>
981 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | PHP pdo mysql helper class
2 | ==========================
3 |
4 |
5 | I add some codes to supports transaction.
6 |
7 | roydu
8 | 2014-04-18
9 |
10 |
11 | Usage
12 | =====
13 | Make sure you've change the configuration file config.php.
14 | Include config.php to your php code
15 |
16 | SELECT
17 | ------
18 |
19 | **standard query**
20 | ```
21 | //this will get all records with username wildan
22 | $data=array('username'=>'wildan');
23 | $custom=$db->query("select * from admin where username=?",$data);
24 | foreach ($custom as $key) {
25 | echo $key->username; //print username column
26 | }
27 | ```
28 | **join 2 table**
29 | ```
30 | //get all record from 2 tables with join
31 | $qr="select admin.*,level.* from admin inner join level on admin.level=level.id_level";
32 | $cust=$db->query($qr);
33 | foreach ($cust as $key) {
34 | echo $key->username.":".$key->name_level;
35 | }
36 | ```
37 | **join 2 tables with condition**
38 | ```
39 | //get all record with condition (admin.level=2)
40 | $qr="select admin.*,level.* from admin inner join level on admin.level=level.id_level and admin.level=?";
41 | $cust=$db->query($qr,array('admin.level'=>2));
42 | foreach ($cust as $key) {
43 | echo $key->username.":".$key->name_level; //print username column and levelname
44 | }
45 | ```
46 | **Retrieving All Rows From A Table**
47 | ```
48 | //equal to select * from admin
49 | $rs=$db->fetchAll('admin');
50 | foreach ($rs as $key) {
51 | echo $key->username.":".$key->password."
";
52 | }
53 | ```
54 | **Retrieving A Single Row From A Table**
55 | ```
56 | //only return one row
57 | //select * from admin where id_user=4
58 | $rs=$db->fetchSingleRow('admin','id_user',4);
59 | echo $rs->username;
60 | ```
61 | **CHECK EXIST**
62 | ```
63 | //select username,password where username='$username' and password='$password'
64 | //return true if exist
65 | //case login system
66 | $data=array(
67 | 'username'=>$_POST['username'],
68 | 'password'=>md5($_POST['password'])
69 | );
70 | $s=$db->checkExist('admin',$data);
71 | if ($s==true) {
72 | echo "good";
73 | } else {
74 | echo "wrong";
75 | }
76 | ```
77 | **Search Record**
78 | ```
79 | 1. search one cond
80 | //search data
81 | //select username,password from admin where username like %wild%
82 | $find=$db->search('admin',array('username','password'),array('username'=>'wild'));
83 | foreach ($find as $key) {
84 | echo $key->username;
85 | }
86 | 2. search multi cond
87 | //select username,password from admin where username like %wild% OR password LIKE %ad%
88 | $find=$db->search('admin',array('username','password'),array('username'=>'wild','password'=>'ad'));
89 | foreach ($find as $key) {
90 | echo $key->username;
91 | }
92 | ```
93 | INSERT
94 | ------
95 | ```
96 | //equal to insert into admin (username,password,level) values('admin',md5('admin'),1)
97 | $data=array('username'=>'admin',
98 | 'password'=>md5('admin'),
99 | 'level'=>1);
100 | $db->insert('admin',$data);
101 |
102 | ```
103 | INSERT Multipe array in one query
104 | ------
105 | ```
106 | //insert multiple array data with single query
107 | $level = array('Operator',"Front Staff");
108 | foreach ($level as $lv) {
109 | $array_data[] = array(
110 | 'name_level' => $lv
111 | );
112 | }
113 | $db->insertMulti('level',$array_data);
114 |
115 |
116 | ```
117 | GET LAST INSERT ID
118 | ------
119 | ```
120 | //equal to insert into admin (username,password,level) values('admin',md5('admin'),1)
121 | $data=array('username'=>'admin',
122 | 'password'=>md5('admin'),
123 | 'level'=>1);
124 | $db->insert('admin',$data);
125 | $last_id = $db->getLastInsertId(); //this will get the last insert id from admin table
126 |
127 | ```
128 |
129 | UPDATE
130 | ------
131 | ```
132 | //equal to update admin set username='wildan',level=1 where id_user=1
133 | $data=array('username'=>'wildan',
134 | 'level'=>1);
135 | $db->update('admin',$data,'id_user',1);
136 |
137 | ```
138 | DELETE
139 | ------
140 | ```
141 | //delete from admin where id_user=1
142 | $db->delete('admin','id_user',1);
143 | ```
144 |
145 |
146 | COMPLEX QUERY
147 | ------
148 | ```
149 | //if you have complex query, you can use query. You can use custom query as complex as u want, and also absolutely with prepared statement for security reason. below is the sample how to use custom query.
150 |
151 | //fetch data
152 | $data = array('id'=>1,'level'=>1);
153 | $db->query("select * from admin where id=? and level=?",$data);
154 |
155 | //insert data,
156 | $data=array('username'=>'admin',
157 | 'password'=>md5('admin'),
158 | 'level'=>1);
159 | $db->query("insert into admin (username,password) values(?,?)",$data);
160 |
161 |
162 | //custom query update data,
163 | $data=array('username'=>'wildan',
164 | 'level'=>2,
165 | 'id'=>1);
166 | $db->query("update admin set username=?,level=? where id=?",$data);
167 |
168 | //delete data
169 | $data=array('id'=>1);
170 | $db->query("delete from admin where id=?",$data);
171 |
172 | ```
173 |
174 | #### Developed By
175 | ----------------
176 | * wildantea -
177 |
--------------------------------------------------------------------------------
/config.php:
--------------------------------------------------------------------------------
1 | getMessage();
18 | }
19 |
20 | set_exception_handler('handleException');
21 |
--------------------------------------------------------------------------------
/db.sql:
--------------------------------------------------------------------------------
1 | -- phpMyAdmin SQL Dump
2 | -- version 3.5.2.2
3 | -- http://www.phpmyadmin.net
4 | --
5 | -- Host: 127.0.0.1
6 | -- Generation Time: Jun 09, 2013 at 10:52 AM
7 | -- Server version: 5.5.27
8 | -- PHP Version: 5.4.7
9 |
10 | SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
11 | SET time_zone = "+00:00";
12 |
13 |
14 | /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
15 | /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
16 | /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
17 | /*!40101 SET NAMES utf8 */;
18 |
19 | --
20 | -- Database: `latihan`
21 | --
22 |
23 | -- --------------------------------------------------------
24 |
25 | --
26 | -- Table structure for table `admin`
27 | --
28 |
29 | CREATE TABLE IF NOT EXISTS `admin` (
30 | `id_user` int(10) NOT NULL AUTO_INCREMENT,
31 | `username` varchar(30) DEFAULT '0',
32 | `password` varchar(32) DEFAULT '0',
33 | `level` int(11) DEFAULT NULL,
34 | PRIMARY KEY (`id_user`),
35 | KEY `FK_admin_level` (`level`)
36 | ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
37 |
38 | --
39 | -- Dumping data for table `admin`
40 | --
41 |
42 | INSERT INTO `admin` (`id_user`, `username`, `password`, `level`) VALUES
43 | (4, 'admin tea dua', '21232f297a57a5a743894a0e4a801fc3', 1),
44 | (5, 'wildan', '21232f297a57a5a743894a0e4a801fc3', 1),
45 | (7, 'user', 'ee11cbb19052e40b07aac0ca060c23ee', 2);
46 |
47 | -- --------------------------------------------------------
48 |
49 | --
50 | -- Table structure for table `level`
51 | --
52 |
53 | CREATE TABLE IF NOT EXISTS `level` (
54 | `id_level` int(10) NOT NULL AUTO_INCREMENT,
55 | `name_level` varchar(50) DEFAULT NULL,
56 | PRIMARY KEY (`id_level`)
57 | ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
58 |
59 | --
60 | -- Dumping data for table `level`
61 | --
62 |
63 | INSERT INTO `level` (`id_level`, `name_level`) VALUES
64 | (1, 'admin'),
65 | (2, 'user');
66 |
67 | --
68 | -- Constraints for dumped tables
69 | --
70 |
71 | --
72 | -- Constraints for table `admin`
73 | --
74 | ALTER TABLE `admin`
75 | ADD CONSTRAINT `FK_admin_level` FOREIGN KEY (`level`) REFERENCES `level` (`id_level`) ON DELETE SET NULL ON UPDATE CASCADE;
76 |
77 | /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
78 | /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
79 | /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
80 |
--------------------------------------------------------------------------------
/sample.php:
--------------------------------------------------------------------------------
1 | CHECK EXIST
";
7 | //select username,password where username='$username' and password='$password'
8 | //return true if exist
9 | //case login system
10 | $data=array(
11 | 'username'=>$_POST['username'],
12 | 'password'=>md5($_POST['password'])
13 | );
14 | $s=$db->checkExist('admin',$data);
15 | if ($s==true) {
16 | echo "good";
17 | } else {
18 | echo "bad";
19 | }
20 | echo "";
21 |
22 |
23 | echo "
";
24 | echo "
fetch all
";
25 | //select * from admin
26 | $rs=$db->fetchAll('admin');
27 | foreach ($rs as $key) {
28 | echo $key->username.":".$key->password."
";
29 | }
30 |
31 | echo "";
32 | echo "
select single row
";
33 | //only return one row
34 | //select * from admin where id_user=4
35 | $rs=$db->fetchSingleRow('admin','id_user',4);
36 | echo $rs->username;
37 |
38 |
39 |
40 | echo "";
41 | echo "
select search data
";
42 | //search data
43 | //select username,password from admin where username like %wild%
44 | $find=$db->search('admin',array('username','password'),array('username'=>'wild'));
45 | foreach ($find as $key) {
46 | echo $key->username;
47 | }
48 |
49 | echo "";
50 | echo "
CUSTOM QUERY
";
51 | //custom query
52 | $vr=array('name'=>'wildan');
53 | $custom=$db->query("select * from admin where username=?",$vr);
54 | foreach ($custom as $key) {
55 | echo $key->username;
56 | }
57 | echo "";
58 | //join table
59 | $qr="select admin.*,level.* from admin inner join level on admin.level=level.id_level and admin.level=?";
60 | $cust=$db->query($qr,array('admin.level'=>2));
61 | foreach ($cust as $key) {
62 | echo $key->username.":".$key->name_level;
63 | }
64 |
65 | $qr="select admin.*,level.* from admin inner join level on admin.level=level.id_level";
66 | $cust=$db->query($qr);
67 | foreach ($cust as $key) {
68 | echo $key->username.":".$key->name_level;
69 | }
70 | ?>
71 |
--------------------------------------------------------------------------------