-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd_record.php
More file actions
88 lines (71 loc) · 2.31 KB
/
Copy pathadd_record.php
File metadata and controls
88 lines (71 loc) · 2.31 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
<?php
declare(strict_types=1);
/**
* Inserts a new row into a table.
*/
require __DIR__ . '/lib/bootstrap.php';
use DbManager\Page;
use DbManager\Schema;
use DbManager\View;
[$pdo, $database, $table] = Page::table();
$columns = Schema::columns($pdo, $table);
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
Page::handle(
static function () use ($pdo, $table, $columns): string {
Schema::insert($pdo, $table, fn_record_values($columns, $_POST));
return __('record.added');
},
url('view_table_data.php', ['db' => $database, 'table' => $table])
);
}
/**
* Maps the submitted form fields onto column values.
*
* Auto increment columns left empty are dropped so the server assigns them, and
* a ticked "set NULL" box wins over whatever the text input holds.
*
* @param array<int, array<string, mixed>> $columns Column definitions.
* @param array<string, mixed> $input Raw POST payload.
*
* @return array<string, string|null> Column => value map ready for the query.
*/
function fn_record_values(array $columns, array $input): array
{
$submitted = is_array($input['values'] ?? null) ? $input['values'] : [];
$nulls = is_array($input['nulls'] ?? null) ? $input['nulls'] : [];
$values = [];
foreach ($columns as $column) {
$name = (string) $column['name'];
if (!array_key_exists($name, $submitted)) {
continue;
}
$raw = (string) $submitted[$name];
$isAuto = str_contains(strtolower((string) $column['extra']), 'auto_increment');
if (isset($nulls[$name])) {
$values[$name] = null;
continue;
}
if ($raw === '' && ($isAuto || $column['default'] !== null)) {
continue;
}
$values[$name] = $raw;
}
return $values;
}
View::render(
'record_form',
[
'database' => $database,
'table' => $table,
'columns' => $columns,
'values' => [],
'keyInputs' => [],
'action' => url('add_record.php'),
'submit' => __('record.save'),
'cancel' => url('view_table_data.php', ['db' => $database, 'table' => $table]),
],
[
'title' => __('record.add_title', [':table' => $table]),
'active' => 'databases',
]
);