Repository navigation
Expand file tree
/
Copy pathSQLiteEdit.php
More file actions
4291 lines (3044 loc) · 148 KB
/
Copy pathSQLiteEdit.php
File metadata and controls
4291 lines (3044 loc) · 148 KB
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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// ***************************************
// * SQLite Edit for PHP *
// * *
// * This is free code - it's released *
// * to the public domain (ie the same *
// * license as SQLite itself). Do with *
// * it as you wish. *
// * *
// * © Richard Heyes 2026 *
// * *
// * https://www.rgraph.net/sqliteedit *
// ***************************************
class SQLiteEdit
{
//
// The ID of this instance
//
public $id;
//
// The path to the database file.
//
public $database_file;
//
// The database table that you want to use.
//
public $database_table;
//
// These are all of the database table columns.
//
public $database_columns;
//
// These are all of the selected columns in the result set.
//
public $database_selected_columns;
//
// The connection reference to the database.
//
public $sqlite;
//
// The database object.
//
public $db;
//
// The options that are givwen to the constructor that
// determine the way that the editor behaves.
//
public $options;
//
// This will hold a copy of the original options, after
// they've been set by the user, but before they have
// been touched by this library.
//
public $options_original;
//
// This is the unique ID for this SQLiteEdit instance
//
public static $counter = 1;
//
// Used to store the order by column once it has been
// calculated.
//
public $ordering_column;
//
// Used to store the order by direction once it has been
// calculated.
//
public $ordering_dir;
//
// The table structure
//
public $structure;
//
// Has a file upload been stipulated. This contains the
// field name(s)
//
public $editable_types_file = [];
//
// The constructor
//
// @param $options array The options to configure the editor
//
public function __construct($options)
{
$this->options = $options;
}
//
// Draws the editor
//
public function draw()
{
$options = $this->options;
$this->database_file = $options['filename'];
$this->database_table = $options['table'];
// Default options
$this->options = [
'filename' => null,
'table' => null,
'primary_key' => null,
'sql_select' => "SELECT * FROM {table} WHERE {where} {order}",
'sql_insert' => null, // This gets built based on the table structure
'sql_delete' => "DELETE FROM {table} WHERE {primary_key} IN({ids}) LIMIT {count}",
'sql_update' => "UPDATE {table} SET {column} = {value} WHERE {primary_key} = {id}",
'editable' => [],
'editable_save_url' => null,
'editable_types' => [],
'editable_types_file_callbacks' => [],
'editable_types_select_options' => [],
'editable_types_radio_options' => [],
'editable_types_checkbox_options' => [],
'editable_view_only' => false,
'editable_event' => 'dblclick',
'editable_callback' => null,
'columns_names' => [],
'columns_widths' => [],
'columns_tooltips' => null,
'columns_callbacks' => [],
'columns_escape' => [],
'paging_current' => 1,
'paging_perpage' => 25,
'paging_numpages' => null,
'paging_info_colspan' => 999,
'search' => true,
'search_columns' => null,
'search_callback' => null,
'ordering_column' => null,
'ordering_dir' => null,
'ordering_include' => null,
'ordering_exclude' => null,
'ordering_changeable' => true,
'ordering_case' => false,
'style' => [],
'actions' => [],
'checkboxes' => false,
'checkboxes_radio' => false,
'events' => []
];
// Add the user specified options
foreach ($options as $k => $v) {
$this->options[$k] = $v;
}
// Remove the "on" from the start of the event name in
// case the user has given "onclick" or "ondblclick"
$this->options['editable_event'] = preg_replace('/^on/', '', $this->options['editable_event']);
// Now make a copy of the starting options to the
// options_original array.
foreach ($this->options as $k => $v) {
$this->options_original[$k] = $v;
}
//
// The id is used as an anchor to this sqliteedit
//
$this->id = 'editor' . SQLiteEdit::$counter++;
// If the order_dir is equal to one then change to be empty
if ($this->options['ordering_dir'] == 'none') {
$this->options['ordering_dir'] = '';
}
// Replace mixed or upper case macros with lower case
// versions in the SQL queries.
//
foreach (['sql_select','sql_insert','sql_update','sql_delete'] as $s) {
if (is_string($this->options[$s])) {
$this->options[$s] = preg_replace_callback('/{[-a-z_0-9]+}/i', function ($matches)
{
return strtolower($matches[0]);
}, $this->options[$s]);
}
}
if ($this->options['paging_current'] < 1) {
$this->options['paging_current'] = 1;
}
// Get the number from the query string. Override
// the page set in the paging_current setting.
if (!empty($_GET[$this->qs('paging')])) {
if (!preg_match('/^[0-9]+$/', $_GET[$this->qs('paging')])) {
$url = new editor_url($_SERVER['REQUEST_URI']);
$url->removequerystringparameter($this->qs('paging'));
$url->setAnchor($this->id);
$u = $url->get();
editor_redirect($u);
}
$this->options['paging_current'] = $_GET[$this->qs('paging')];
if ($this->options['paging_current'] < 1) {
$this->options['paging_current'] = 1;
}
// This should be enough...
if ($this->options['paging_current'] > 1000000000) {
$this->options['paging_current'] = 1;
$url = new editor_url($_SERVER['REQUEST_URI']);
$url->removequerystringparameter($this->qs('paging'));
$url->setAnchor($this->id);
$u = $url->get();
editor_redirect($u);
}
}
//
// Open the database.
//
$this->db = editor_database::open($this->database_file);
//
// Determine the columns that make up the table
//
$this->database_columns = $this->db->column(sprintf(
"PRAGMA table_info(%s)",
$this->database_table
),
'name'
);
//
// Now get the fulll structure of the table
//
$this->getStructure();
//
// Now the structure has been determined build the
// default insert query.
//
if (is_null($this->options['sql_insert'])) {
$this->options['sql_insert'] = $this->buildInsertQuery();
}
//
// Determine the primary key field by looking at the
// pragma information.
//
if (empty($this->options['primary_key'])) {
$result = $this->db->query(sprintf(
"PRAGMA table_info('%s')",
$this->database_table
)
);
while($row = $this->db->fetchArray($result)) {
if ($row['pk']) {
$this->options['primary_key'] = $row['name'];
}
}
}
//
// Allow the use of * in the various properties
//
foreach (['columns_tooltips', 'columns_widths','editable_types','editable','search_columns', 'ordering_include', 'ordering_exclude','columns_callbacks','columns_escape'] as $column) {
if (is_array($this->options[$column])) {
foreach ($this->options[$column] as $k => $v) {
if (trim($k) === '*') {
foreach ($this->database_columns as $c) {
if (!isset($this->options[$column][$c])) {
$this->options[$column][$c] = $v;
}
}
// Get rid of the asterisk
unset($this->options[$column]['*']);
}
}
}
}
//
// Determine if a file type input has been set in the
// editable_types option. If it has - idicate that the
// form encoding type should be multipart/form-data
//
foreach ($this->options['editable_types'] as $k => $v) {
if ($v === 'file') {
$this->editable_types_file[] = $k;
}
}
// First, if the request is a POST then handle that. It
// will be an edit of a row.
if ( !empty($this->options['editable'])
AND !$this->options['editable_view_only']
AND $this->options['sql_update']
AND !empty($_POST)
AND !empty($_POST['editor_action'])
AND $_POST['editor_action'] === 'save'
AND !empty($_POST['editor_id'])
AND $_POST['editor_id'] === $this->id
) {
$ret = $this->fireEvent('beforeupdate', [
'data' => $_POST['data'],
'editor_primary_key_column' => $_POST['editor_primary_key_column'],
'editor_primary_key_value' => $_POST['editor_primary_key_value']
]);
// Must be exactly false
if ($ret !== false) {
// Call the callback for a file upload to allow
// the user to do what they want with it. Whatever
// the callback returns is stored in the database.
if ($this->editable_types_file) {
foreach ($_FILES as $k => $v) {
if (!empty($this->options['editable_types'][$k]) AND $this->options['editable_types'][$k] === 'file' AND !empty($this->options['editable_types_file_callbacks'][$k]) AND is_callable($this->options['editable_types_file_callbacks'][$k])) {
$ret = $this->options['editable_types_file_callbacks'][$k]($this, $k, $_FILES[$k]);
if ($ret) {
$_POST['data'][$k] = $ret;
}
}
}
}
//
// First, go through the POST data and add blank
// entries if there are checkboxes in the
// configuration but nothing has been submitted.
// The browser won't send anything if no checkboxes
// were checked so this needs to be done for when
// there's something in the database but no
// checkboxes were checked. In that case, nothing
// would change for that field normally but it
// needs to be set to nothing in case theres
// already something in that field.
//
foreach ($this->options['editable_types'] as $k => $v) {
if ( ($v === 'checkbox' OR $v === 'radio') AND !isset($_POST['data'][$k])) {
$_POST['data'][$k] = '';
}
}
// Pass the data to the editable_callback function,
// if its defined. if this function returns a
// falsey value then the save SQL is not run.
//
// If the sql_update option is a function then it's
// not called.
//
if (is_callable($this->options['editable_callback'])) {
$callback_return = $this->options['editable_callback']($this, $_POST['data']);
}
if (!isset($callback_return) OR is_null($callback_return) OR $callback_return) {
if (is_callable($this->options['sql_update'])) {
$this->options['sql_update'](
$this,
$_POST['data'],
$_POST['editor_primary_key_column'],
$_POST['editor_primary_key_value']
);
$this->fireEvent('update', [
'data' => $_POST['data'],
'editor_primary_key_column' => $_POST['editor_primary_key_column'],
'editor_primary_key_value' => $_POST['editor_primary_key_value']
]);
} else {
// Initially set this to true. If any query
// fails it's set to false.
$final_result = true;
$sqliteErrorMessages = [];
if (!empty($_POST['data'])) {
foreach ($_POST['data'] as $k => $v) {
// Only allow values that have been
// designated as being editable are allowed
// to be saved.
if (!isset($this->options['editable'][$k]) OR !$this->options['editable'][$k]) {
continue;
}
// Convert datetime formats
if (!is_array($v) AND preg_match('/(\d\d\d\d-\d\d-\d\d)(?: |T)(\d\d:\d\d)((?::\d\d)?)/', $v, $matches)) {
$_POST['data'][$k] = sprintf('%s %s', $matches[1], $matches[2]);
// Add seconds
if (!$matches[3]) {
$_POST['data'][$k] .= ':00';
}
}
$sql = str_ireplace('{table}', $this->options['table'], $this->options['sql_update']);
$sql = str_ireplace('{column}', $k, $sql);
$sql = str_ireplace('{value}', "'" . SQLite3::escapeString(is_array($v) ? implode(',', $v): $v) . "'", $sql);
$sql = str_ireplace('{id}', (is_integer($_POST['editor_primary_key_value']) OR is_numeric($_POST['editor_primary_key_value'])) ? intval($_POST['editor_primary_key_value']) : "'" . SQLite3::escapeString($_POST['editor_primary_key_value']) . "'", $sql);
$sql = str_ireplace('{primary_key}',$_POST['editor_primary_key_column'], $sql);
// Run the SQL query to update the
// database.
//
// **********************************
// * This is now done automatically *
// * on the editor_database object. *
// **********************************
//
try {
$result = $this->db->query($sql);
} catch (Exception $e) {
$sqliteErrorMessages[] = $e->getMessage();
}
$final_result = $final_result && empty($sqliteErrorMessages);
}
}
if ($final_result) {
editor_messages::success($this->id, 'The database was updated');
$this->fireEvent('update', [
'data' => $_POST['data'],
'editor_primary_key_column' => $_POST['editor_primary_key_column'],
'editor_primary_key_value' => $_POST['editor_primary_key_value']
]);
} else {
foreach ($sqliteErrorMessages as $e) {
editor_messages::error($this->id, 'The update failed (SQLite said: ' . $e . ').');
}
}
}
}
}
// Redirect back to the referring page
//
// Build the URL to redirect back to.
//
$url = new editor_url();
$url->removequerystringparameter('r');
$url->addquerystringparameter('r', mt_rand(999999, 1999999999));
$redirectTo = $url->get();
//editor_redirect($url->get());
editor_redirect($redirectTo . '#' . $this->id);
exit;
}
foreach (['editable_types_select_options', 'editable_types_radio_options', 'editable_types_checkbox_options'] as $p) {
foreach ($this->options[$p] as $k => $v){
if (gettype($this->options[$p][$k]) === 'string' AND preg_match('|^\s*sql\s*:|', $this->options[$p][$k])) {
$query = preg_replace('|^\s*sql\s*:|','',$this->options[$p][$k]);
$results = $this->db->column($query);
$this->options[$p][$k] = $results;
}
}
}
// Add a new row by running the given SQL (in
// the configuration).
if ($this->options['sql_insert'] AND !empty($_GET[$this->qs('add')]) AND $_GET[$this->qs('add')] === $this->id) {
$ret = $this->fireEvent('beforeinsert');
if ($ret !== false) {
if (is_callable($this->options['sql_insert'])) {
$this->options['sql_insert']($this);
$this->fireEvent('insert');
} else if (is_string($this->options['sql_insert']) AND $this->options['sql_insert']) {
$sqliteErrorMessage = false;
try {
$result = $this->db->query($this->options['sql_insert']);
}catch (Exception $e) {
$sqliteErrorMessage = $e->getMessage();
}
if (!$sqliteErrorMessage) {
$this->fireEvent('insert');
editor_messages::success($this->id, 'A new row was added');
} else {
editor_messages::error($this->id, 'The addition failed (SQLite said: ' . $sqliteErrorMessage . ').');
}
}
}
// Build the URL to redirect back to.
//
$url = new editor_url();
$url->removequerystringparameter($this->qs('add'));
$url->setanchor($this->id);
editor_redirect($url->get());
exit;
}
//
// Build the SQL for the delete from what has been
// given in the configuration.
//
if ($this->options['sql_delete'] AND !empty($this->options['sql_delete']) AND !empty($_GET[$this->qs('action')]) AND $_GET[$this->qs('action')] === 'delete' AND $_GET[$this->qs('id', false)] === $this->id) {
if (!empty($_GET[$this->qs('delete')])) {
$ids = $_GET[$this->qs('delete')];
$ret = $this->fireEvent('beforedelete', ['ids' => $ids]);
if ($ret !== false AND !empty ($ids)) {
if (is_callable($this->options['sql_delete'])) {
$this->options['sql_delete']($this, $ids);
$this->fireEvent('delete', ['ids' => $ids]);
} else if (is_string($this->options['sql_delete'])) {
// If any of the submitted IDs are not numeric
// then quote them.
foreach ($ids as &$v) {
if (!is_numeric($v)) {
$v = $this->db->quote($v);
}
}
$sql = str_ireplace('{table}', $this->options['table'], $this->options['sql_delete']);
$sql = str_ireplace('{ids}', implode(',', $ids), $sql);
$sql = str_ireplace('LIMIT {count}', 'LIMIT ' . count($ids), $sql);
$sql = str_ireplace('{primary_key}',$this->options['primary_key'], $sql);
$sqliteErrorMessage = false;
try {
$result = $this->db->query($sql);
}catch (Exception $e) {
$sqliteErrorMessage = $e->getMessage();
}
if (!$sqliteErrorMessage) {
$affected = $this->db->changes();
editor_messages::success($this->id, $affected > 1 ? $affected . ' rows were deleted' : 'That row was deleted');
$this->fireEvent('delete', ['ids' => $ids]);
} else {
editor_messages::error($this->id, 'The delete failed (SQLite said: ' . $sqliteErrorMessage . ').');
}
}
} else if ($ret !== false AND empty($ids)) {
editor_messages::error($this->id, 'No rows were selected!');
}
}
// Build the URL to redirect back to
$url = new editor_url();
$url->removequerystringparameter($this->qs('action'));
$url->removequerystringparameter($this->qs('delete'));
$url->setanchor($this->id);
editor_redirect($url->get());
exit;
}
//
// Determines the order by part of the query from the
// options and the query-string.
//
$this->addOrdering();
//
// Print the list of database rows in the requested
// table.
//
//
$this->printTable();
}
//
// Fires on event (eg ondelete)
//
// @param $name string The name of the evnt to fire.
// @param $extra array Any extra information to pass to the
// registered event listener(s).
//
function fireEvent($name, $extra = null)
{
$events = $this->options['events'];
$name = preg_replace('/^on/', '', $name);
$ret = null;
// If the event has had the "on" word added to the name
// accommodate that.
if (empty($this->options['events'][$name]) AND !empty($this->options['events']['on' . $name])) {
$this->options['events'][$name] = $this->options['events']['on' . $name];
}
if (!empty($this->options['events'][$name])) {
if (!empty($this->options['events'][$name]) AND is_callable($this->options['events'][$name])) {
$ret = ($this->options['events'][$name])($this, $extra);
}
}
return $ret;
}
//
// Shows the HTML header
//
public function header()
{
?>
<!-- <div style="height: 25px"> </div> -->
<?php
editor_messages::display($this->id);
}
//
// Shows the HTML footer
//
public function footer()
{
}
//
// This function determines if a column can be ordered by
// based on the ordering include and ordering exclude
// properties.
//
// @param string name The column name
// @return bool Whether the column can be ordered
// by or not
//
function orderingIncludeExclude($name)
{
$result = false;
//
// Inclusions
//
$include_null = is_null($this->options['ordering_include']);
$include_asterisk = isset($this->options['ordering_include']) && is_array($this->options['ordering_include']) && !empty($this->options['ordering_include']['*']);
$include_column = isset($this->options['ordering_include']) && is_array($this->options['ordering_include']) && !empty($this->options['ordering_include'][$name]);
if ($include_null OR $include_asterisk OR $include_column) {
$result = true;
}
//
// Exclusions
//
if (isset($this->options['ordering_exclude'])) {
$exclude_asterisk = is_array($this->options['ordering_exclude']) && !empty($this->options['ordering_exclude']['*']);
$exclude_column = is_array($this->options['ordering_exclude']) && !empty($this->options['ordering_exclude'][$name]);
if ($exclude_asterisk OR $exclude_column) {
$result = false;
}
}
// Having an asterisk in the ordering_include array
// allows all columns to be orderable
//if (is_array($this->options['ordering_include']) AND in_array('*', $this->options['ordering_include'])) {
// $result = true;
//} elseif (is_array($this->options['ordering_include'])) {
//if (is_array($this->options['ordering_include'])) {
// if (in_array($name, $this->options['ordering_include'])) {
// $result = true;
// } else {
// $result = false;
// }
//}
//if (in_array($name, (array)$this->options['ordering_exclude']) OR in_array('*', (array)$this->options['ordering_exclude'])) {
//if (in_array($name, (array)$this->options['ordering_exclude'])) {
// $result = false;
//}
return $result;
}
//
// Determines the correct order by part of the query and
// adds it.
//
public function addOrdering ()
{
// Get the ID of this editor instance
$id = $this->id;
if ( stripos($this->options['sql_select'],'{order}') > 0
AND (@$_GET[$this->qs('order_column')] !== 'none')
AND (@$_GET[$this->qs('order_dir')] !== 'none')) {
// Start by getting the order by from the
// configuration.
$order_column = !empty($this->options['ordering_column']) ? $this->options['ordering_column'] : '';
$order_dir = !empty($this->options['ordering_dir']) ? $this->options['ordering_dir'] : 'asc';
// If the order_column is set on the QS - use it
// (is the ordering_changeable property is set to
// false).
if (!empty($this->options['ordering_changeable']) AND !empty($_GET[$this->qs('order_column')]) AND preg_match('/^[a-z0-9]+$/', $_GET[$this->qs('order_column')])) {
$order_column = $_GET[$this->qs('order_column')];
}
// If the order_dir is set on the QS - use it.
if (!empty($this->options['ordering_changeable'])) {
if (!empty($_GET[$this->qs('order_dir')]) AND preg_match('/^asc|desc$/i', $_GET[$this->qs('order_dir')])) {
$order_dir = strtoupper($_GET[$this->qs('order_dir')]);
} else if (!empty($this->options['ordering_dir'])) {
$order_dir = @strtolower($this->options['ordering_dir']);
} else {
$order_dir = 'asc';
}
}
// Order by column and dir have been given so use
// them in the query. But if the column is in the
// exclude array - ignore it.
if (!empty($order_column) AND !empty($order_dir) AND $this->orderingIncludeExclude($order_column)) {
$this->options['sql_select'] = str_ireplace(
'{order}',
sprintf(
'ORDER BY %s %s %s ',
$order_column,
($this->options['ordering_case'] ? '' : 'COLLATE NOCASE'),
$order_dir
),
$this->options['sql_select']
);
// No order given so just lose the {order} from the
// query.
} else {
$this->options['sql_select'] = str_ireplace(
'{order}',
'',
$this->options['sql_select']
);
}
// Get rid of the {order}
} else if (stripos($this->options['sql_select'],'{order}') > 0) {
$this->options['sql_select'] = str_ireplace(
'{order}',
'',
$this->options['sql_select']
);
}
$this->ordering_column = !empty($order_column) ? $order_column : '';
$this->ordering_dir = !empty($order_dir) ? $order_dir : '';
}
//
// Builds the structure of the table
//
public function getStructure ()
{
$result = $this->db->all(
sprintf(
"PRAGMA table_info(%s)",
$this->database_table
)
);
$this->structure = $result;
}
//
// Builds the default insert query based on the structure.
// All the values are blank by default.
//
public function buildInsertQuery ()
{
$fields = $this->database_columns;
$fields_str = '';
$values = [];
//
// Add all of the field names to the query
//
$fields_str = implode(', ', $fields);
$sql = sprintf(
'INSERT INTO %s (%s) values({values})',
$this->options['table'],
$fields_str
);
//
// Now add default field values into the query
//
$values_str = '';
$values = [];
foreach($this->structure as $f) {
switch (strtolower($f['type'])) {
case 'real':
case 'integer':
$values[] = $f['pk'] ? 'NULL' : ($f['dflt_value'] ? $f['dflt_value'] : 0);
break;
case 'null':
$values[] = ($f['dflt_value'] ? $f['dflt_value'] : 'NULL');
break;
case 'blob':
case 'text':
$values[] = ($f['dflt_value'] ? $f['dflt_value'] : "''");
break;
}
}
// Add the values to the SQL query
$sql = str_replace('{values}', implode(',', $values), $sql);
return $sql;
}
//
// Shows the table
//
// printData
//
public function printTable ()
{
$html = '';
$columns = array();
$sql = $this->options['sql_select'];
// Replace the {table} macro in the SQL with the name
// of the table.
$sql = str_ireplace('{table}',$this->options['table'], $sql);