Skip to content

Commit

Permalink
add create_record method at Table
Browse files Browse the repository at this point in the history
  • Loading branch information
gusalbukrk committed Feb 13, 2023
1 parent c2aecff commit c6c54d5
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 5 deletions.
12 changes: 8 additions & 4 deletions www/Table/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,6 @@ protected function tables()

protected function records()
{
echo "<pre>";
print_r($_POST);
echo "</pre>";

$db = explode(".", $_SERVER["HTTP_HOST"])[0];
$db_exists = $this->model->db_exists($db);

Expand All @@ -90,6 +86,14 @@ protected function records()
$table_exists = $db_exists ? $this->model->table_exists($db, $table) : false;

if ($db_exists && $table_exists) {
if (isset($_POST["action"])) {
$action = $_POST["action"];

if ($action === "create") {
$this->model->create_record($db, $table, $_POST["record"]);
}
}

$schema = $this->model->get_columns_schema($db, $table);
$records = $this->model->get_records($db, $table);
}
Expand Down
12 changes: 12 additions & 0 deletions www/Table/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,4 +154,16 @@ public function table_exists($db, $table)
// $stmt->fetch returns false if no record was found
return $stmt->fetch(\PDO::FETCH_COLUMN) !== false;
}

// function relies on the fact that the fields in $record are preserved on the correct order
// they've been fetched using `SHOW COLUMNS`, looped in JS and then dynamically layered in the form
public function create_record($db, $table, $record)
{
$stmt = $this->conn->prepare(
"INSERT INTO $db.$table VALUES (" .
preg_replace("/, $/", "", str_repeat("?, ", count($record))) .
")"
);
$stmt->execute(array_values($record));
}
}
2 changes: 1 addition & 1 deletion www/views/Table/records.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@

const input = document.createElement('input');
input.type = types[column.Type.replace(/\(\d+\)$/, '')];
input.name = column.Field;
input.name = `record[${column.Field}]`;
input.setAttribute('form', 'createForm');

cell.appendChild(input);
Expand Down

0 comments on commit c6c54d5

Please sign in to comment.