V cvičení cv07 aplikácia zapisuje do databázy cez INSERT a číta z nej cez SELECT. V cvičení cv08 pribudne úprava cez UPDATE a mazanie cez DELETE. Postup je rozdelený na časti: unifikácia názvov files, UPDATE a DELETE pre lookup table (číselník), UPDATE a DELETE pre main entity (hlavná entita) aj s pivot table (prepojka). Po cv08 je aplikácia hotová, pribudne do nej už len JavaScript. Pojmy sú v tabuľke v týždni 1.
Príklady sú z aplikácie lezecká stena (vzor cv08). Každý file je uvedený názvom a rolou, napr. data.php (lookup tables) alebo detail.php (main entity). Druhý príklad, knižnica, ukazuje to isté pravidlo v inej aplikácii. Odsek „Vo svojej aplikácii” pri každom postupe hovorí, čo sa mení pre iné tables.
In lab cv07 the application writes to the database with INSERT and reads from it with SELECT. Lab cv08 adds editing with UPDATE and deleting with DELETE. The work is split into parts: unification of file names, UPDATE and DELETE for a lookup table, UPDATE and DELETE for the main entity including the pivot table. After cv08 the application is complete, only JavaScript will be added to it. Terms are in the table in week 1.
The examples come from the climbing wall application (sample cv08). Every file is referred to by its name and role, e.g. data.php (lookup tables) or detail.php (main entity). A second example, a library, shows the same rule in another application. The paragraph “In your own application” after each procedure says what changes for other tables.
TeóriaTheory
CRUD: operácie s records
CRUD je skratka z anglických slov Create, Read, Update, Delete. Sú to operácie, ktoré aplikácia robí s records v databáze. Každej zodpovedá jeden SQL príkaz.
| Operation | SQL | Čo sa stane v table | File v aplikácii (rola) | Od cvičenia |
|---|---|---|---|---|
| Create | INSERT |
pribudne nový record | data.php (lookup tables), add-route.php (main entity) |
cv07 |
| Read | SELECT |
records sa vypíšu, table sa nezmení | routes.php, detail.php (main entity), data.php (lookup tables), stats.php (prehľad) |
cv07 |
| Update | UPDATE |
zmenia sa hodnoty v existujúcom record | edit-grade.php, edit-style.php (lookup tables), edit-route.php (main entity) |
cv08 |
| Delete | DELETE |
record sa zmaže | delete-grade.php, delete-style.php (lookup tables), delete-route.php (main entity) |
cv08 |
Create v skratke CRUD znamená nový record v table, teda INSERT. Príkaz CREATE TABLE vytvára table a do CRUD nepatrí.
Lookup table aj main entity potrebujú každú z týchto operácií. V cv07 majú INSERT a SELECT, v cv08 dostanú UPDATE a DELETE.
Z čoho sa aplikácia skladá
Aplikácia je priečinok web/. Každý file v ňom má jednu rolu.
Spoločné files. Používa ich každá stránka, v prehliadači sa neotvárajú.
db.php: pripojenie k databáze, vytvorí$pdo,template.php: template (šablóna) každej stránky, vypíše<head>, menu,<h1>s titulkom, content file a footer,css/style.css: vlastné CSS k Bootstrap.
Stránky. Stránku tvorí file stránky web/X.php a content file web/content/X.php s rovnakým názvom. File stránky sa otvára v prehliadači: pripojí db.php, nastaví $title, $active, $content a pripojí template.php. Content file obsahuje PHP, ktoré komunikuje s databázou, a HTML stránky.
Files bez stránky. delete-grade.php, delete-style.php a delete-route.php vykonajú DELETE a pošlú prehliadač na inú adresu. Nič nevypisujú, preto content file nemajú.
Čo do aplikácie nepatrí. form.php a content/register.php (registrácia z cv05, aplikácia ju nepoužíva), priečinok practice/, kópie files a pokusy. V repository zostáva len to, čo aplikácia používa.
Názov file je daný rolou. Píše sa anglicky, malými písmenami, bez diakritiky, slová spája pomlčka. V tabuľke je ENTITY názov table main entity a LOOKUP názov lookup table. Zoznam main entity má názov table (routes.php). Files add-, edit- a delete- pracujú s jedným record, preto majú názov v jednotnom čísle (add-route.php).
| Rola | File | CRUD | Lezecká stena | Knižnica |
|---|---|---|---|---|
| main entity, zoznam s filtrom | ENTITY.php |
Read | routes.php |
books.php |
| main entity, detail jedného record | detail.php |
Read | detail.php |
detail.php |
| main entity, formulár na nový record | add-ENTITY.php |
Create | add-route.php |
add-book.php |
| main entity, formulár na úpravu jedného record | edit-ENTITY.php |
Update | edit-route.php |
edit-book.php |
| main entity, zmazanie jedného record | delete-ENTITY.php |
Delete | delete-route.php |
delete-book.php |
| lookup tables, formuláre na nový record a výpis tables | data.php |
Create, Read | data.php |
data.php |
| lookup table, formulár na úpravu jedného record | edit-LOOKUP.php |
Update | edit-grade.php, edit-style.php |
edit-genre.php, edit-tag.php |
| lookup table, zmazanie jedného record | delete-LOOKUP.php |
Delete | delete-grade.php, delete-style.php |
delete-genre.php, delete-tag.php |
| prehľad, výpisy s JOIN a GROUP BY | stats.php |
Read | stats.php |
stats.php |
| úvodná stránka | index.php |
index.php |
index.php |
|
| stránka s kontaktom | contact.php |
contact.php |
contact.php |
|
| pripojenie k databáze | db.php |
db.php |
db.php |
|
| template | template.php |
template.php |
template.php |
Tables v príkladoch: lezecká stena má main entity routes, lookup tables grades a styles a pivot table route_styles. Knižnica má main entity books, lookup tables genres a tags a pivot table book_tags.
Každý file vo vzore začína komentárom s rolou, CRUD operáciou a miestom, odkiaľ sa otvára. Rovnaký komentár patrí do každého file vo svojej aplikácii.
Ako vzniká stránka (opakovanie)
Príklad: používateľ klikne v data.php (lookup tables) na odkaz Upraviť pri grade 6b.
- Prehliadač pošle request na adresu
edit-grade.php?id=3. - Server spustí file stránky
web/edit-grade.php. Ten pripojídb.php(vznikne$pdo), nastaví$title,$active,$contenta pripojítemplate.php. template.phpvypíše začiatok HTML:<head>, menu a<h1>s titulkom.template.phpvloží content filecontent/edit-grade.php. PHP v ňom prečítaidz URL, pošle SQL databáze a vypíše HTML s formulárom.template.phpvypíše footer a koniec HTML.- Server pošle HTML ako response a prehliadač ho zobrazí.
Formulár v content/edit-grade.php má method="post" a nemá action. Po kliknutí na Uložiť zmeny ide request na tú istú adresu edit-grade.php?id=3 a kroky 1 až 6 sa zopakujú, tentoraz s hodnotami z formulára v $_POST. Rovnako pracuje formulár v content/add-route.php z cv07.
HTML sa začína vypisovať v kroku 3. Táto informácia je dôležitá v časti o redirect.
UPDATE: zmena hodnôt v existujúcom record
UPDATE grades SET name = '6b+', value = 6.4 WHERE id = 3;
Za SET sú columns a ich nové hodnoty. WHERE určuje record, v ktorom sa hodnoty zmenia. UPDATE bez WHERE zmení hodnoty v každom record table, preto má UPDATE v aplikácii vždy WHERE id = ?.
V PHP sa UPDATE posiela cez prepare a execute ako INSERT v cv07. Hodnoty v execute idú v poradí otáznikov, id je posledné, lebo posledný otáznik patrí k WHERE:
$stmt = $pdo->prepare('UPDATE grades SET name = ?, value = ? WHERE id = ?');
$stmt->execute([$name, $value, $id]);
Hodnoty prichádzajú z rôznych miest:
| Hodnota | Odkiaľ je | V PHP |
|---|---|---|
id record, ktorý sa upravuje |
z URL, odkaz Upraviť v data.php má adresu edit-grade.php?id=3 |
$_GET['id'] |
| nové hodnoty columns | z formulára method="post" |
$_POST['name'], $_POST['value'] |
Formulár na úpravu je ten istý ako formulár na nový record, len má v každom input hodnotu z databázy. Kam sa hodnota píše, závisí od elementu:
| Element | Kam patrí hodnota z databázy | Príklad |
|---|---|---|
input |
attribute value |
value="<?= htmlspecialchars($grade['name']) ?>" |
textarea |
medzi tagy | <textarea>...</textarea>, attribute value textarea nemá |
select |
attribute selected pri jednom option |
<?= $grade['id'] == $route['grade_id'] ? 'selected' : '' ?> |
checkbox |
attribute checked |
<?= in_array($style['id'], $routeStyleIds) ? 'checked' : '' ?> |
Content file na úpravu má vždy toto poradie:
idz URL do premennej.- Ak prišiel formulár (
POST): hodnoty z$_POSTdo premenných, kontrola, UPDATE, správa do$message. - SELECT record podľa
id. - HTML: správa a formulár s hodnotami z kroku 3.
SELECT je za UPDATE. Formulár preto po uložení ukazuje hodnoty, ktoré sú po UPDATE v databáze.
Column name v lookup table je UNIQUE. Pred UPDATE sa preto kontroluje, či rovnaký name má iný record:
SELECT id FROM grades WHERE name = '5a' AND id <> 3;
Na dátach zo seed.sql vráti record s id 1: name 5a už má iný record. Operátor <> znamená „nerovná sa”. Podmienka id <> 3 vynechá upravovaný record. Bez nej by SELECT našiel aj record, ktorý sa práve upravuje, a uloženie formulára bez zmeny name by skončilo správou, že hodnota už existuje.
Viac: MariaDB: UPDATE
Správa po každej operácii
Po každej operácii, ktorá mení dáta, aplikácia vypíše správu. Používateľ z nej vie, že operácia bola vykonaná, alebo prečo vykonaná nebola. Správa je div s Bootstrap classes alert alert-info.
| Operácia | File, ktorý ju vykoná | Kde sa správa zobrazí | Odkiaľ je text správy |
|---|---|---|---|
| INSERT do lookup table | content/data.php |
v data.php, nad formulármi |
premenná $message v tom istom file |
| INSERT do main entity | content/add-route.php |
v add-route.php, nad formulárom |
premenná $message v tom istom file |
| UPDATE lookup table | content/edit-grade.php |
v edit-grade.php?id=3, nad formulárom |
premenná $message v tom istom file |
| UPDATE main entity | content/edit-route.php |
v edit-route.php?id=2, nad formulárom |
premenná $message v tom istom file |
| DELETE z lookup table | delete-grade.php |
v data.php, pod <h1> |
array $messages v template.php, key z URL |
| DELETE z main entity | delete-route.php |
v routes.php, pod <h1> |
array $messages v template.php, key z URL |
INSERT a UPDATE vykoná content file a správu vypíše v tej istej stránke. DELETE vykoná file bez stránky, ktorý nič nevypisuje. Správa sa preto zobrazí až na stránke, ktorú prehliadač otvorí po DELETE. Postup je v časti o redirect.
DELETE: zmazanie record
DELETE FROM styles WHERE id = 3;
Na dátach zo seed.sql tento príkaz zmaže style boulder.
WHERE určuje record, ktorý sa zmaže. DELETE bez WHERE zmaže každý record table, preto má DELETE v aplikácii vždy WHERE id = ?.
Odkaz v HTML posiela GET request. Adresu z odkazu otvorí prehliadač znova z histórie alebo zo záložky a prejde ju aj vyhľadávač. Keby mazal odkaz delete-style.php?id=3, každé otvorenie tejto adresy by zmazalo record. Operácia, ktorá mení dáta, sa preto posiela cez POST.
Button Zmazať je malý formulár. id record nesie hidden input, ako hodnotu form vo formulároch v content/data.php z cv07:
<form method="post" action="delete-grade.php">
<input type="hidden" name="id" value="3">
<button class="btn btn-outline-danger btn-sm">Zmazať</button>
</form>
File delete-grade.php číta id z $_POST['id']. Keď ho niekto otvorí cez adresu (GET), nič nezmaže a pošle prehliadač späť na data.php.
Record sa po kliknutí zmaže hneď. Otázka „naozaj zmazať?” pred odoslaním formulára pribudne v týždni o JavaScript.
Viac: MariaDB: DELETE
Obmedzenia pri DELETE
Foreign keys v sql/schema.sql z cv06 určujú, čo databáza spraví pri DELETE record, na ktorý ukazuje iný record.
| Maže sa record v table | Ukazuje naň | Nastavenie v schema.sql | Čo spraví databáza |
|---|---|---|---|
grades (lookup table) |
routes.grade_id |
ON DELETE RESTRICT |
DELETE odmietne, kým má tento grade aspoň jedna cesta |
styles (lookup table) |
route_styles.style_id |
ON DELETE RESTRICT |
DELETE odmietne, kým je tento style aspoň v jednej dvojici |
routes (main entity) |
route_styles.route_id |
ON DELETE CASCADE |
zmaže cestu a s ňou jej dvojice v pivot table |
Odmietnutý DELETE vráti chybu SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails a skript sa zastaví. Aplikácia preto pred DELETE z lookup table zistí cez SELECT, či je record použitý:
SELECT COUNT(*) AS routes_count FROM routes WHERE grade_id = 1;
Na dátach zo seed.sql vráti routes_count 2 (Žltá hrana a Zelená platňa majú grade 5a). Keď je počet väčší ako 0, DELETE sa nevykoná a používateľ dostane správu „Záznam sa nedá zmazať, je použitý.”
Pri main entity kontrola nie je potrebná. Na record v routes ukazuje len pivot table a tá má CASCADE.
Redirect: funkcia header
File delete-grade.php vykoná DELETE a nič nevypíše. Používateľ má po zmazaní vidieť data.php (lookup tables) s aktuálnym obsahom table grades. delete-grade.php preto pošle prehliadaču namiesto HTML adresu, ktorú má otvoriť. Volá sa to redirect (presmerovanie).
header('Location: data.php?msg=deleted');
exit;
header()je funkcia PHP. Pridá do response riadok s informáciou pre prehliadač (HTTP header). RiadokLocationobsahuje adresu. Prehliadač po takej response pošle nový GET request na túto adresu.exitukončí skript. Bezexitby PHP pokračovalo ďalším riadkom file.
header() funguje, len kým PHP nezačalo vypisovať HTML. V stránke zloženej cez template.php sa HTML začína vypisovať v kroku 3 a content file je na rade v kroku 4. V content file je preto na redirect neskoro a PHP vypíše Warning: Cannot modify header information - headers already sent. Redirect patrí do file bez stránky: delete-grade.php pripája len db.php, template nepripája a pred header() nič nevypíše.
Celý priebeh po kliknutí na button Zmazať v data.php:
- Prehliadač pošle POST request na
delete-grade.phpsidv hidden input. delete-grade.phpzistí cez SELECT, či je record použitý.- Ak je použitý:
header('Location: data.php?msg=used')aexit. - Ak použitý nie je: vykoná sa DELETE, potom
header('Location: data.php?msg=deleted')aexit. - Prehliadač pošle GET request na adresu z
Location. - Vznikne stránka
data.phpkrokmi 1 až 6 z časti Ako vzniká stránka.template.phpvypíše pod<h1>správu.
Správa po redirect. Redirect je nový request. Premenné z delete-grade.php v ňom už neexistujú, správa v premennej by sa stratila. Informácia o výsledku preto ide v URL ako parameter msg: data.php?msg=deleted. Text správy je v template.php v array $messages, kde key je hodnota z URL a value je text:
$messages = [
'deleted' => 'Záznam bol zmazaný.',
'used' => 'Záznam sa nedá zmazať, je použitý.',
];
$msg = $_GET['msg'] ?? '';
$text = $messages[$msg] ?? '';
$messages[$msg] ?? '' vráti text ku key z URL. Keď taký key v array nie je, vráti prázdny text a správa sa nevypíše.
- Správa je v
template.php, lebo po DELETE z lookup table sa otváradata.phpa po DELETE z main entityroutes.php. Template je spoločný, správa sa zobrazí v oboch. - Správa je pod
<h1>, lebo tam ju používateľ uvidí hneď po otvorení stránky, pred obsahom z content file. - V URL je key, text správy nie. Text v URL môže ktokoľvek prepísať a stránka by ho vypísala. S key sa vypíše len text, ktorý je v array.
Po redirect je v adresnom riadku data.php?msg=deleted. Obnovenie stránky cez F5 zopakuje len tento GET request, DELETE sa znova nevykoná.
Viac: php.net: header
UPDATE main entity a pivot table
Formulár na úpravu main entity mení columns v routes a zaškrtnuté checkboxy, teda dvojice v pivot table route_styles. Po odoslaní formulára sa vykonajú tieto príkazy:
UPDATE routes SET name = ?, holds = ?, grade_id = ?, since = ?, note = ? WHERE id = ?;
DELETE FROM route_styles WHERE route_id = ?;
INSERT INTO route_styles (route_id, style_id) VALUES (?, ?);
UPDATE zmení columns cesty. DELETE zmaže každú dvojicu tejto cesty v pivot table. INSERT sa vykoná vo foreach pre každý zaškrtnutý checkbox, rovnako ako v content/add-route.php z cv07. Po týchto príkazoch sú v pivot table presne tie dvojice, ktoré sú zaškrtnuté vo formulári.
Na zaškrtnutie správnych checkboxov sú potrebné id styles tejto cesty. Použijú sa funkcie PHP pre array:
| Funkcia | Čo vráti | Príklad na dátach zo seed.sql (cesta s id 2) |
|---|---|---|
array_column($rows, 'style_id') |
array hodnôt jednej column z tabuľky records | z [['style_id' => 1], ['style_id' => 2]] vráti [1, 2] |
in_array($value, $array) |
true, keď hodnota v array je, inak false |
in_array(2, [1, 2]) vráti true, in_array(3, [1, 2]) vráti false |
Viac: php.net: array_column, php.net: in_array
Unifikácia názvov files
Files aplikácie vznikali od cv03 a ich názvy nemajú spoločné pravidlo. Pred doplnením UPDATE a DELETE sa preto názvy zjednotia podľa tabuľky rolí. Tento krok sa volá unifikácia. Vykoná ju script unify.py, ktorý je v repository cv08.
Script sa spúšťa v termináli Kubeflow v priečinku repository cv08.
| Príkaz | Čo spraví |
|---|---|
python3 unify.py --init |
vytvorí unify.txt: tables zo sql/schema.sql a zoznam files vo web/ s návrhom nového názvu |
python3 unify.py |
vypíše plán podľa unify.txt, files nemení |
python3 unify.py --run |
vykoná plán |
python3 unify.py --check |
skontroluje odkazy a dvojice file stránky a content file, files nemení |
unify.txt je plán unifikácie. Pri každom file je za šípkou nový názov alebo slovo zmazat. Otáznik je pri file, pre ktorý script nový názov neurčil. Otáznik sa nahradí názvom podľa tabuľky rolí.
python3 unify.py --run spraví toto:
- premenuje files cez
git mv, história commitov zostane, - zmaže files označené
zmazat, - v každom file nahradí starý názov novým: v menu v
template.php, v$content,href,action,require,includeaheader, - vytvorí files, ktoré podľa tabuľky rolí v aplikácii chýbajú; file na úpravu a zmazanie obsahuje komentár
DOPLŇ v úlohe, - na začiatok každého file doplní komentár s rolou, CRUD operáciou a miestom, odkiaľ sa otvára,
- do
README.mdzapíše mapu aplikácie: file, rola, CRUD, - skontroluje, či každý odkaz vedie na existujúci file, a vypíše, čo treba dokončiť.
Script mení názvy files, odkazy na ne a komentár na začiatku file. Ostatný kód zostáva bez zmeny.
Najčastejšie chyby a čo znamenajú
| Hláška alebo prejav | Príčina | Riešenie |
|---|---|---|
Warning: Cannot modify header information - headers already sent |
header() je zavolaná po začiatku HTML: v content file, alebo je pred <?php prázdny riadok |
redirect patrí do file bez stránky; pred <?php nesmie byť nič |
Cannot delete or update a parent row: a foreign key constraint fails |
DELETE record z lookup table, ktorý je použitý (RESTRICT) |
pred DELETE kontrola cez SELECT COUNT(*) |
Invalid parameter number |
počet otáznikov v SQL a počet hodnôt v execute([...]) je rôzny |
spočítať otázniky, id pre WHERE na koniec |
| po uložení majú rovnaké hodnoty viaceré records | UPDATE nemá WHERE id = ? |
doplniť WHERE; dáta obnoviť cez schema.sql a seed.sql v Adminer |
| formulár po uložení ukazuje staré hodnoty | SELECT record je pred UPDATE | poradie v content file: UPDATE, potom SELECT |
„už existuje” pri uložení bez zmeny name |
kontrola duplicity nemá AND id <> ? |
doplniť podmienku a $id do execute |
Warning: Undefined array key "id" |
stránka na úpravu otvorená bez ?id= v URL |
$id = $_GET['id'] ?? ''; a kontrola if (!$grade) |
button Zmazať len otvorí data.php, record zostal |
button je odkaz (GET), alebo hidden input nemá name="id" |
formulár method="post" s <input type="hidden" name="id"> |
| po zmazaní sa správa nezobrazí | key v URL nie je v array $messages, alebo template.php správu nevypisuje |
porovnať msg= v header() s keys v $messages |
| vo formulári na úpravu nie je zaškrtnutý žiadny checkbox | chýba in_array(...) ? 'checked' : '' alebo array_column |
doplniť podľa ukážky 7 |
unify.py: „odkaz na X, taký file vo web/ nie je” |
v kóde je odkaz na file, ktorý neexistuje | opraviť názov v odkaze, potom python3 unify.py --check |
CRUD: operations on records
CRUD stands for Create, Read, Update, Delete. These are the operations an application performs on records in a database. Each one corresponds to one SQL statement.
| Operation | SQL | What happens in the table | File in the application (role) | Since lab |
|---|---|---|---|---|
| Create | INSERT |
a new record is added | data.php (lookup tables), add-route.php (main entity) |
cv07 |
| Read | SELECT |
records are listed, the table does not change | routes.php, detail.php (main entity), data.php (lookup tables), stats.php (overview) |
cv07 |
| Update | UPDATE |
values in an existing record change | edit-grade.php, edit-style.php (lookup tables), edit-route.php (main entity) |
cv08 |
| Delete | DELETE |
the record is deleted | delete-grade.php, delete-style.php (lookup tables), delete-route.php (main entity) |
cv08 |
Create in CRUD means a new record in a table, that is INSERT. The statement CREATE TABLE creates a table and is not part of CRUD.
A lookup table and the main entity both need every one of these operations. In cv07 they have INSERT and SELECT, in cv08 they get UPDATE and DELETE.
What the application consists of
The application is the folder web/. Every file in it has one role.
Shared files. Every page uses them; they are not opened in the browser.
db.php: the database connection, creates$pdo,template.php: the template of every page, prints<head>, the menu,<h1>with the title, the content file and the footer,css/style.css: custom CSS on top of Bootstrap.
Pages. A page consists of the page file web/X.php and the content file web/content/X.php with the same name. The page file is opened in the browser: it includes db.php, sets $title, $active, $content and includes template.php. The content file holds the PHP that talks to the database and the HTML of the page.
Files without a page. delete-grade.php, delete-style.php and delete-route.php execute DELETE and send the browser to another address. They print nothing, so they have no content file.
What does not belong in the application. form.php and content/register.php (the registration from cv05, the application does not use it), the folder practice/, copies of files and experiments. The repository keeps only what the application uses.
The name of a file is given by its role. It is written in English, in lowercase, without diacritics, words joined by a hyphen. In the table ENTITY is the name of the main entity table and LOOKUP the name of a lookup table. The list of the main entity has the name of the table (routes.php). The files add-, edit- and delete- work with one record, so they use the singular (add-route.php).
| Role | File | CRUD | Climbing wall | Library |
|---|---|---|---|---|
| main entity, list with a filter | ENTITY.php |
Read | routes.php |
books.php |
| main entity, detail of one record | detail.php |
Read | detail.php |
detail.php |
| main entity, form for a new record | add-ENTITY.php |
Create | add-route.php |
add-book.php |
| main entity, form to edit one record | edit-ENTITY.php |
Update | edit-route.php |
edit-book.php |
| main entity, deleting one record | delete-ENTITY.php |
Delete | delete-route.php |
delete-book.php |
| lookup tables, forms for a new record and listing of tables | data.php |
Create, Read | data.php |
data.php |
| lookup table, form to edit one record | edit-LOOKUP.php |
Update | edit-grade.php, edit-style.php |
edit-genre.php, edit-tag.php |
| lookup table, deleting one record | delete-LOOKUP.php |
Delete | delete-grade.php, delete-style.php |
delete-genre.php, delete-tag.php |
| overview, listings with JOIN and GROUP BY | stats.php |
Read | stats.php |
stats.php |
| home page | index.php |
index.php |
index.php |
|
| contact page | contact.php |
contact.php |
contact.php |
|
| database connection | db.php |
db.php |
db.php |
|
| template | template.php |
template.php |
template.php |
Tables in the examples: the climbing wall has the main entity routes, the lookup tables grades and styles and the pivot table route_styles. The library has the main entity books, the lookup tables genres and tags and the pivot table book_tags.
Every file in the sample starts with a comment stating the role, the CRUD operation and where the file is opened from. The same comment belongs in every file of your own application.
How a page is built (revision)
Example: in data.php (lookup tables) the user clicks the link Upraviť (Edit) next to grade 6b.
- The browser sends a request to the address
edit-grade.php?id=3. - The server runs the page file
web/edit-grade.php. It includesdb.php($pdois created), sets$title,$active,$contentand includestemplate.php. template.phpprints the beginning of the HTML:<head>, the menu and<h1>with the title.template.phpincludes the content filecontent/edit-grade.php. Its PHP readsidfrom the URL, sends SQL to the database and prints the HTML with the form.template.phpprints the footer and the end of the HTML.- The server sends the HTML as the response and the browser displays it.
The form in content/edit-grade.php has method="post" and no action. After clicking Uložiť zmeny (Save changes) the request goes to the same address edit-grade.php?id=3 and steps 1 to 6 are repeated, this time with the form values in $_POST. The form in content/add-route.php from cv07 works the same way.
The HTML starts being printed in step 3. This matters in the part about redirect.
UPDATE: changing values in an existing record
UPDATE grades SET name = '6b+', value = 6.4 WHERE id = 3;
After SET come the columns and their new values. WHERE determines the record in which the values change. UPDATE without WHERE changes the values in every record of the table, so UPDATE in the application always has WHERE id = ?.
In PHP UPDATE is sent with prepare and execute like INSERT in cv07. The values in execute follow the order of the question marks; id is last because the last question mark belongs to WHERE:
$stmt = $pdo->prepare('UPDATE grades SET name = ?, value = ? WHERE id = ?');
$stmt->execute([$name, $value, $id]);
The values come from different places:
| Value | Where it comes from | In PHP |
|---|---|---|
id of the record being edited |
from the URL, the link Upraviť in data.php has the address edit-grade.php?id=3 |
$_GET['id'] |
| new values of the columns | from the form with method="post" |
$_POST['name'], $_POST['value'] |
The edit form is the same as the form for a new record, only every input holds a value from the database. Where the value goes depends on the element:
| Element | Where the value from the database goes | Example |
|---|---|---|
input |
the attribute value |
value="<?= htmlspecialchars($grade['name']) ?>" |
textarea |
between the tags | <textarea>...</textarea>, a textarea has no attribute value |
select |
the attribute selected on one option |
<?= $grade['id'] == $route['grade_id'] ? 'selected' : '' ?> |
checkbox |
the attribute checked |
<?= in_array($style['id'], $routeStyleIds) ? 'checked' : '' ?> |
A content file for editing always has this order:
idfrom the URL into a variable.- If the form arrived (
POST): values from$_POSTinto variables, validation, UPDATE, a message into$message. - SELECT of the record by
id. - HTML: the message and the form with the values from step 3.
SELECT comes after UPDATE. After saving, the form therefore shows the values that are in the database after the UPDATE.
The column name in a lookup table is UNIQUE. Before UPDATE the application therefore checks whether another record has the same name:
SELECT id FROM grades WHERE name = '5a' AND id <> 3;
On the data from seed.sql it returns the record with id 1: another record already has the name 5a. The operator <> means “not equal”. The condition id <> 3 leaves out the record being edited. Without it SELECT would also find the record that is being edited, and saving the form without changing name would end with the message that the value already exists.
More: MariaDB: UPDATE
A message after every operation
After every operation that changes data the application prints a message. It tells the user that the operation was executed, or why it was not. The message is a div with the Bootstrap classes alert alert-info.
| Operation | File that executes it | Where the message is shown | Where the text comes from |
|---|---|---|---|
| INSERT into a lookup table | content/data.php |
in data.php, above the forms |
the variable $message in the same file |
| INSERT into the main entity | content/add-route.php |
in add-route.php, above the form |
the variable $message in the same file |
| UPDATE of a lookup table | content/edit-grade.php |
in edit-grade.php?id=3, above the form |
the variable $message in the same file |
| UPDATE of the main entity | content/edit-route.php |
in edit-route.php?id=2, above the form |
the variable $message in the same file |
| DELETE from a lookup table | delete-grade.php |
in data.php, below <h1> |
the array $messages in template.php, key from the URL |
| DELETE from the main entity | delete-route.php |
in routes.php, below <h1> |
the array $messages in template.php, key from the URL |
INSERT and UPDATE are executed by a content file, which prints the message in the same page. DELETE is executed by a file without a page, which prints nothing. The message is therefore shown on the page the browser opens after the DELETE. The procedure is in the part about redirect.
DELETE: deleting a record
DELETE FROM styles WHERE id = 3;
On the data from seed.sql this statement deletes the style boulder.
WHERE determines the record that is deleted. DELETE without WHERE deletes every record of the table, so DELETE in the application always has WHERE id = ?.
A link in HTML sends a GET request. The browser opens the address of a link again from history or from a bookmark, and a search engine crawls it too. If the link delete-style.php?id=3 did the deleting, every opening of that address would delete a record. An operation that changes data is therefore sent with POST.
The button Zmazať (Delete) is a small form. The id of the record is carried by a hidden input, like the value form in the forms in content/data.php from cv07:
<form method="post" action="delete-grade.php">
<input type="hidden" name="id" value="3">
<button class="btn btn-outline-danger btn-sm">Zmazať</button>
</form>
The file delete-grade.php reads id from $_POST['id']. When somebody opens it through the address (GET), it deletes nothing and sends the browser back to data.php.
The record is deleted immediately after the click. The question “really delete?” before the form is submitted comes in the JavaScript week.
More: MariaDB: DELETE
Restrictions on DELETE
The foreign keys in sql/schema.sql from cv06 determine what the database does on DELETE of a record that another record points to.
| Record deleted in table | Pointed to by | Setting in schema.sql | What the database does |
|---|---|---|---|
grades (lookup table) |
routes.grade_id |
ON DELETE RESTRICT |
refuses the DELETE while at least one route has this grade |
styles (lookup table) |
route_styles.style_id |
ON DELETE RESTRICT |
refuses the DELETE while this style is in at least one pair |
routes (main entity) |
route_styles.route_id |
ON DELETE CASCADE |
deletes the route and with it its pairs in the pivot table |
A refused DELETE returns the error SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails and the script stops. Before DELETE from a lookup table the application therefore finds out with SELECT whether the record is used:
SELECT COUNT(*) AS routes_count FROM routes WHERE grade_id = 1;
On the data from seed.sql it returns routes_count 2 (Žltá hrana and Zelená platňa have grade 5a). When the count is greater than 0, DELETE is not executed and the user gets the message “Záznam sa nedá zmazať, je použitý.” (The record cannot be deleted, it is used.)
For the main entity no check is needed. Only the pivot table points to a record in routes, and it has CASCADE.
Redirect: the function header
The file delete-grade.php executes DELETE and prints nothing. After deleting, the user should see data.php (lookup tables) with the current content of the table grades. Instead of HTML, delete-grade.php therefore sends the browser the address it should open. This is called a redirect.
header('Location: data.php?msg=deleted');
exit;
header()is a PHP function. It adds a line with information for the browser (an HTTP header) to the response. The lineLocationcontains an address. After such a response the browser sends a new GET request to that address.exitends the script. WithoutexitPHP would continue with the next line of the file.
header() works only until PHP has started printing HTML. In a page assembled through template.php the HTML starts being printed in step 3 and the content file runs in step 4. In a content file it is therefore too late for a redirect and PHP prints Warning: Cannot modify header information - headers already sent. A redirect belongs in a file without a page: delete-grade.php includes only db.php, does not include the template and prints nothing before header().
The whole sequence after clicking the button Zmazať in data.php:
- The browser sends a POST request to
delete-grade.phpwithidin the hidden input. delete-grade.phpfinds out with SELECT whether the record is used.- If it is used:
header('Location: data.php?msg=used')andexit. - If it is not used: DELETE is executed, then
header('Location: data.php?msg=deleted')andexit. - The browser sends a GET request to the address from
Location. - The page
data.phpis built by steps 1 to 6 from the part How a page is built.template.phpprints the message below<h1>.
The message after a redirect. A redirect is a new request. The variables from delete-grade.php no longer exist in it, a message in a variable would be lost. The information about the result therefore travels in the URL as the parameter msg: data.php?msg=deleted. The text of the message is in template.php in the array $messages, where the key is the value from the URL and the value is the text:
$messages = [
'deleted' => 'Záznam bol zmazaný.',
'used' => 'Záznam sa nedá zmazať, je použitý.',
];
$msg = $_GET['msg'] ?? '';
$text = $messages[$msg] ?? '';
$messages[$msg] ?? '' returns the text for the key from the URL. When the array has no such key, it returns an empty text and no message is printed.
- The message is in
template.phpbecause after DELETE from a lookup tabledata.phpis opened and after DELETE from the main entityroutes.php. The template is shared, so the message is shown in both. - The message is below
<h1>because there the user sees it right after the page opens, before the content from the content file. - The URL carries the key, not the text of the message. Anyone can rewrite text in a URL and the page would print it. With a key only a text that is in the array is printed.
After the redirect the address bar shows data.php?msg=deleted. Reloading the page with F5 repeats only this GET request; DELETE is not executed again.
More: php.net: header
UPDATE of the main entity and the pivot table
The edit form of the main entity changes the columns in routes and the checked checkboxes, that is the pairs in the pivot table route_styles. After the form is submitted these statements are executed:
UPDATE routes SET name = ?, holds = ?, grade_id = ?, since = ?, note = ? WHERE id = ?;
DELETE FROM route_styles WHERE route_id = ?;
INSERT INTO route_styles (route_id, style_id) VALUES (?, ?);
UPDATE changes the columns of the route. DELETE deletes every pair of this route in the pivot table. INSERT is executed in a foreach for every checked checkbox, the same way as in content/add-route.php from cv07. After these statements the pivot table holds exactly the pairs that are checked in the form.
Checking the right checkboxes requires the id values of the styles of this route. PHP functions for arrays are used:
| Function | What it returns | Example on the data from seed.sql (route with id 2) |
|---|---|---|
array_column($rows, 'style_id') |
an array of the values of one column from a table of records | from [['style_id' => 1], ['style_id' => 2]] it returns [1, 2] |
in_array($value, $array) |
true when the value is in the array, otherwise false |
in_array(2, [1, 2]) returns true, in_array(3, [1, 2]) returns false |
More: php.net: array_column, php.net: in_array
Unification of file names
The files of the application have been created since cv03 and their names follow no common rule. Before UPDATE and DELETE are added, the names are therefore unified according to the table of roles. This step is called unification. It is carried out by the script unify.py, which is in the repository cv08.
The script is run in the Kubeflow terminal in the folder of the repository cv08. Its output is in Slovak.
| Command | What it does |
|---|---|
python3 unify.py --init |
creates unify.txt: the tables from sql/schema.sql and the list of files in web/ with a proposed new name |
python3 unify.py |
prints the plan from unify.txt, changes no files |
python3 unify.py --run |
carries out the plan |
python3 unify.py --check |
checks the links and the pairs of page file and content file, changes no files |
unify.txt is the plan of the unification. After the arrow each file has its new name or the word zmazat (delete). A question mark stands next to a file for which the script did not determine a new name. Replace the question mark with a name from the table of roles.
python3 unify.py --run does this:
- renames files with
git mv, the commit history stays, - deletes the files marked
zmazat, - replaces the old name with the new one in every file: in the menu in
template.php, in$content,href,action,require,includeandheader, - creates the files that are missing in the application according to the table of roles; a file for editing or deleting contains the comment
DOPLŇ v úlohe(complete in task), - adds a comment with the role, the CRUD operation and where the file is opened from to the beginning of every file,
- writes the map of the application into
README.md: file, role, CRUD, - checks whether every link leads to an existing file and prints what remains to be finished.
The script changes file names, links to them and the comment at the beginning of a file. The rest of the code stays unchanged.
Common errors and what they mean
| Message or symptom | Cause | Fix |
|---|---|---|
Warning: Cannot modify header information - headers already sent |
header() is called after the HTML has started: in a content file, or there is an empty line before <?php |
a redirect belongs in a file without a page; nothing may precede <?php |
Cannot delete or update a parent row: a foreign key constraint fails |
DELETE of a lookup table record that is used (RESTRICT) |
a check with SELECT COUNT(*) before DELETE |
Invalid parameter number |
the number of question marks in the SQL differs from the number of values in execute([...]) |
count the question marks, id for WHERE goes last |
| after saving, several records have the same values | UPDATE has no WHERE id = ? |
add WHERE; restore the data with schema.sql and seed.sql in Adminer |
| after saving, the form shows the old values | SELECT of the record is before UPDATE | order in the content file: UPDATE, then SELECT |
“už existuje” (already exists) when saving without changing name |
the duplicate check has no AND id <> ? |
add the condition and $id to execute |
Warning: Undefined array key "id" |
the edit page opened without ?id= in the URL |
$id = $_GET['id'] ?? ''; and the check if (!$grade) |
the button Zmazať only opens data.php, the record stays |
the button is a link (GET), or the hidden input has no name="id" |
a form with method="post" and <input type="hidden" name="id"> |
| no message after deleting | the key in the URL is not in the array $messages, or template.php does not print the message |
compare msg= in header() with the keys in $messages |
| no checkbox is checked in the edit form | in_array(...) ? 'checked' : '' or array_column is missing |
add them following example 7 |
unify.py: „odkaz na X, taký file vo web/ nie je” |
the code links to a file that does not exist | fix the name in the link, then python3 unify.py --check |
UkážkyExamples
Ukážky sú files aplikácie lezecká stena zo vzoru cv08. Každý file je celý, s komentárom o role na začiatku. Pod kódom je náhľad stránky v prehliadači s adresou, ktorá sa otvorí. Každá ukážka vychádza z dát zo seed.sql: grades 5a, 6a, 6b, styles toprope, lead, boulder, cesty Žltá hrana, Modrý previs, Červená platňa, Zelená platňa.
Ukážka 1: unifikácia vzoru
Vzor pred unifikáciou je stav z cv07 so zvyškami z cv05: form.php, content/register.php, priečinok practice/ a content/home.php s iným názvom, ako má file stránky index.php.
cd cv08
python3 unify.py --init
Script vytvorí unify.txt. Tables určil zo sql/schema.sql. Pri files známych z cvičení navrhol nový názov alebo zmazat:
# unify.txt: plán unifikácie. Riadky so znakom # na začiatku sú komentáre.
#
# 1. Skontroluj tables. Za názvom table je slovo do názvu file (názov v jednotnom čísle).
# Z entity: routes route vzniknú názvy routes.php, add-route.php, edit-route.php, delete-route.php.
entity: routes route
lookup: grades grade
lookup: styles style
# 2. Pri každom file napíš za šípku nový názov podľa pravidla. Namiesto názvu môže byť: zmazat
# Otáznik: script nový názov neurčil. Nahraď ho názvom zo zoznamu na konci alebo slovom zmazat.
# Cesty sú od priečinka web/.
add-route.php -> add-route.php
contact.php -> contact.php
data.php -> data.php
db.php -> db.php
detail.php -> detail.php
form.php -> zmazat
index.php -> index.php
routes.php -> routes.php
stats.php -> stats.php
template.php -> template.php
content/add-route.php -> content/add-route.php
content/contact.php -> content/contact.php
content/data.php -> content/data.php
content/detail.php -> content/detail.php
content/home.php -> content/index.php
content/register.php -> zmazat
content/routes.php -> content/routes.php
content/stats.php -> content/stats.php
practice/loop.php -> zmazat
# Názvy podľa pravidla, ktoré zatiaľ nemá žiadny file. Čo zostane voľné, vytvorí script ako nový file.
# edit-route.php main entity routes, formulár na úpravu jedného record (file stránky)
# content/edit-route.php main entity routes, formulár na úpravu jedného record (content file)
# delete-route.php main entity routes, zmazanie jedného record (file bez stránky)
# edit-grade.php lookup table grades, formulár na úpravu jedného record (file stránky)
# content/edit-grade.php lookup table grades, formulár na úpravu jedného record (content file)
# delete-grade.php lookup table grades, zmazanie jedného record (file bez stránky)
# edit-style.php lookup table styles, formulár na úpravu jedného record (file stránky)
# content/edit-style.php lookup table styles, formulár na úpravu jedného record (content file)
# delete-style.php lookup table styles, zmazanie jedného record (file bez stránky)
python3 unify.py vypíše plán. Files sa pri tom nemenia:
Main entity: routes (slovo do názvu file: route)
Lookup tables: grades (grade), styles (style)
Premenovať:
content/home.php -> content/index.php
Zmazať:
form.php
content/register.php
practice/loop.php
Vytvoriť (v aplikácii chýba):
edit-route.php main entity routes, formulár na úpravu jedného record (file stránky)
content/edit-route.php main entity routes, formulár na úpravu jedného record (content file)
delete-route.php main entity routes, zmazanie jedného record (file bez stránky)
edit-grade.php lookup table grades, formulár na úpravu jedného record (file stránky)
content/edit-grade.php lookup table grades, formulár na úpravu jedného record (content file)
delete-grade.php lookup table grades, zmazanie jedného record (file bez stránky)
edit-style.php lookup table styles, formulár na úpravu jedného record (file stránky)
content/edit-style.php lookup table styles, formulár na úpravu jedného record (content file)
delete-style.php lookup table styles, zmazanie jedného record (file bez stránky)
Zatiaľ sa nič nezmenilo. Ak plán sedí, spusti: python3 unify.py --run
python3 unify.py --run plán vykoná:
Zmeny:
premenovaný: content/home.php -> content/index.php
zmazaný: form.php
zmazaný: content/register.php
zmazaný: practice/loop.php
odkaz opravený v index.php: content/home.php -> content/index.php
vytvorený: edit-route.php
vytvorený: content/edit-route.php
vytvorený: delete-route.php
vytvorený: edit-grade.php
vytvorený: content/edit-grade.php
vytvorený: delete-grade.php
vytvorený: edit-style.php
vytvorený: content/edit-style.php
vytvorený: delete-style.php
komentár s rolou doplnený: add-route.php
komentár s rolou doplnený: contact.php
komentár s rolou doplnený: data.php
komentár s rolou doplnený: db.php
komentár s rolou doplnený: detail.php
komentár s rolou doplnený: index.php
komentár s rolou doplnený: routes.php
komentár s rolou doplnený: stats.php
komentár s rolou doplnený: template.php
komentár s rolou doplnený: content/add-route.php
komentár s rolou doplnený: content/contact.php
komentár s rolou doplnený: content/data.php
komentár s rolou doplnený: content/detail.php
komentár s rolou doplnený: content/index.php
komentár s rolou doplnený: content/routes.php
komentár s rolou doplnený: content/stats.php
mapa aplikácie zapísaná do README.md
Kontrola: každý odkaz vedie na existujúci file, každá stránka má content file.
Ďalej: otvor aplikáciu v prehliadači, prejdi každú položku menu a potom:
git add -A && git commit -m "unifikácia názvov files"
Mapa aplikácie, ktorú script zapísal do README.md:
| file | rola | CRUD |
|---|---|---|
web/db.php |
pripojenie k databáze, spoločný file | žiadna |
web/template.php |
template, spoločný file každej stránky | žiadna |
web/index.php |
úvodná stránka (file stránky) | žiadna |
web/content/index.php |
úvodná stránka (content file) | žiadna |
web/contact.php |
stránka s kontaktom (file stránky) | žiadna |
web/content/contact.php |
stránka s kontaktom (content file) | žiadna |
web/routes.php |
main entity routes, zoznam (file stránky) | Read |
web/content/routes.php |
main entity routes, zoznam (content file) | Read |
web/detail.php |
main entity routes, detail jedného record (file stránky) | Read |
web/content/detail.php |
main entity routes, detail jedného record (content file) | Read |
web/add-route.php |
main entity routes, formulár na nový record (file stránky) | Create |
web/content/add-route.php |
main entity routes, formulár na nový record (content file) | Create |
web/edit-route.php |
main entity routes, formulár na úpravu jedného record (file stránky) | Update |
web/content/edit-route.php |
main entity routes, formulár na úpravu jedného record (content file) | Update |
web/delete-route.php |
main entity routes, zmazanie jedného record (file bez stránky) | Delete |
web/data.php |
lookup tables, formuláre na nový record a výpis tables (file stránky) | Create, Read |
web/content/data.php |
lookup tables, formuláre na nový record a výpis tables (content file) | Create, Read |
web/edit-grade.php |
lookup table grades, formulár na úpravu jedného record (file stránky) | Update |
web/content/edit-grade.php |
lookup table grades, formulár na úpravu jedného record (content file) | Update |
web/delete-grade.php |
lookup table grades, zmazanie jedného record (file bez stránky) | Delete |
web/edit-style.php |
lookup table styles, formulár na úpravu jedného record (file stránky) | Update |
web/content/edit-style.php |
lookup table styles, formulár na úpravu jedného record (content file) | Update |
web/delete-style.php |
lookup table styles, zmazanie jedného record (file bez stránky) | Delete |
web/stats.php |
prehľad, výpisy s JOIN a GROUP BY (file stránky) | Read |
web/content/stats.php |
prehľad, výpisy s JOIN a GROUP BY (content file) | Read |
File, ktorý script vytvoril, má komentár s rolou a miesto na doplnenie. Aplikácia s ním funguje hneď, button Zmazať zatiaľ len vráti prehliadač na data.php:
<?php
// ROLA: lookup table grades, zmazanie jedného record (file bez stránky)
// CRUD: Delete
// OTVÁRA SA: z data.php, button Zmazať (formulár POST s hidden input id)
// DOPLŇ v úlohe 9.6: kontrola, DELETE, redirect so správou
header('Location: data.php'); // zatiaľ len redirect späť
exit;
Vo svojej aplikácii. V unify.txt skontroluj riadky entity a lookup: názov table a slovo do názvu file. Každý otáznik nahraď názvom podľa tabuľky rolí alebo slovom zmazat. File, ktorý do tabuľky rolí nepatrí, ale aplikácia ho používa, zostáva so svojím názvom.
Ukážka 2: template.php so správou po redirect
template.php je spoločný file každej stránky. Oproti cv07 pribudol array $messages na začiatku a výpis správy pod <h1>.
<?php
// ROLA: template, spoločný file každej stránky
// CRUD: žiadna
// OTVÁRA SA: v prehliadači sa neotvára; file stránky ho pripája cez include 'template.php'
// ROBÍ: vypíše <head>, menu, <h1> s titulkom, správu po redirect, content file a footer
// VO SVOJEJ APLIKÁCII: zmeň názov aplikácie a položky menu
$messages = [ // správy, ktoré sa zobrazia po redirect
'deleted' => 'Záznam bol zmazaný.',
'used' => 'Záznam sa nedá zmazať, je použitý.',
];
$msg = $_GET['msg'] ?? ''; // kľúč z URL, napr. data.php?msg=deleted
$text = $messages[$msg] ?? ''; // text k tomu kľúču; neznámy kľúč = prázdny text
?>
<!doctype html>
<html lang="sk">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= $title ?> | Lezecká stena</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<nav class="navbar navbar-expand-md bg-dark navbar-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="index.php">Lezecká stena</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#menu">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="menu">
<ul class="navbar-nav">
<li class="nav-item"><a class="nav-link <?= $active == 'index' ? 'active' : '' ?>" href="index.php">Domov</a></li>
<li class="nav-item"><a class="nav-link <?= $active == 'routes' ? 'active' : '' ?>" href="routes.php">Cesty</a></li>
<li class="nav-item"><a class="nav-link <?= $active == 'add-route' ? 'active' : '' ?>" href="add-route.php">Nová cesta</a></li>
<li class="nav-item"><a class="nav-link <?= $active == 'data' ? 'active' : '' ?>" href="data.php">Databáza</a></li>
<li class="nav-item"><a class="nav-link <?= $active == 'stats' ? 'active' : '' ?>" href="stats.php">Prehľad</a></li>
<li class="nav-item"><a class="nav-link <?= $active == 'contact' ? 'active' : '' ?>" href="contact.php">Kontakt</a></li>
</ul>
</div>
</div>
</nav>
<main class="container">
<h1><?= $title ?></h1>
<?php if ($text !== ''): ?>
<div class="alert alert-info"><?= $text ?></div>
<?php endif; ?>
<?php include $content; ?>
</main>
<footer class="bg-light mt-5">
<div class="container py-3">© <?= date('Y') ?> Lezecká stena</div>
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
Databáza
grades
SELECT * FROM grades
| id | name | value | akcia |
|---|---|---|---|
| 1 | 5a | 5.0 | Upraviť Zmazať |
| 2 | 6a | 6.0 | Upraviť Zmazať |
| 3 | 6b | 6.3 | Upraviť Zmazať |
Takto to vyzerá v prehliadači: otvorená adresa je data.php?msg=used. Pod titulkom Databáza je správa „Záznam sa nedá zmazať, je použitý.” Adresa data.php bez msg a adresa data.php?msg=abc správu nezobrazia, lebo key abc v array $messages nie je.
Vo svojej aplikácii. Do template.php doplň blok PHP s $messages na začiatok file a výpis správy pod <h1>. Texty správ môžu zostať rovnaké.
Ukážka 3: data.php (lookup tables), odkaz Upraviť a button Zmazať
content/data.php z cv07 vypisuje každú table. V cv08 pribudol array $editable s lookup tables a v ich tabuľkách column akcia. isset($array[$key]) vráti true, keď array taký key má.
<?php
// ROLA: lookup tables, formuláre na nový record a výpis všetkých tables (file stránky)
// CRUD: Create, Read
// OTVÁRA SA: z menu, položka Databáza
// ROBÍ: pripojí databázu, nastaví titulok a content file content/data.php
// VO SVOJEJ APLIKÁCII: názov data.php zostáva
require 'db.php'; // pripojenie: content file bude mať $pdo
$title = 'Databáza'; // titulok: vypíše ho template.php v <title> a v <h1>
$active = 'data'; // ktorá položka menu je zvýraznená
$content = 'content/data.php'; // content file tejto stránky
include 'template.php'; // template.php vypíše HTML a vloží content file
<?php
// ROLA: lookup tables, formuláre na nový record a výpis všetkých tables (content file)
// CRUD: Create, Read
// OTVÁRA SA: vkladá ho template.php, keď sa otvorí data.php
// ROBÍ: po odoslaní formulára vykoná INSERT do lookup table; vypíše každú table; v lookup tables má každý record odkaz Upraviť a button Zmazať
// VO SVOJEJ APLIKÁCII: zmeň názvy tables a columns; v $editable uveď svoje lookup tables
$message = ''; // hláška pre používateľa
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['form'] ?? '') === 'grade') { // odoslaný formulár na grade
$name = $_POST['name']; // z input name="name", napr. 7a
$value = $_POST['value']; // z input name="value", napr. 7.0
if ($name === '' || $value === '') {
$message = 'Vyplň grade aj hodnotu.';
} else {
$stmt = $pdo->prepare('SELECT id FROM grades WHERE name = ?'); // existuje už taký grade?
$stmt->execute([$name]);
if ($stmt->fetch()) { // fetch vráti record, alebo false
$message = 'Grade ' . $name . ' už existuje.';
} else {
$stmt = $pdo->prepare('INSERT INTO grades (name, value) VALUES (?, ?)'); // SQL s dvoma otáznikmi
$stmt->execute([$name, $value]); // prvý ? = $name, druhý ? = $value
$message = 'Pridaný grade ' . $name . ' (' . $stmt->rowCount() . ' record).';
}
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['form'] ?? '') === 'style') { // odoslaný formulár na style
$name = $_POST['name'];
if ($name === '') {
$message = 'Vyplň názov style.';
} else {
$stmt = $pdo->prepare('SELECT id FROM styles WHERE name = ?');
$stmt->execute([$name]);
if ($stmt->fetch()) {
$message = 'Style ' . $name . ' už existuje.';
} else {
$stmt = $pdo->prepare('INSERT INTO styles (name) VALUES (?)'); // jeden otáznik
$stmt->execute([$name]);
$message = 'Pridaný style ' . $name . '.';
}
}
}
?>
<?php if ($message !== ''): ?>
<div class="alert alert-info"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>
<h2>Pridať do lookup tables</h2>
<div class="row g-4 mb-4">
<div class="col-md-6">
<form method="post" class="border rounded p-3">
<input type="hidden" name="form" value="grade"> <!-- ktorý z dvoch formulárov bol odoslaný -->
<h3 class="h5">Nový grade</h3>
<div class="mb-2">
<label class="form-label" for="grade-name">Grade</label>
<input class="form-control" id="grade-name" name="name" required>
</div>
<div class="mb-2">
<label class="form-label" for="grade-value">Hodnota na porovnávanie</label>
<input class="form-control" id="grade-value" name="value" type="number" step="0.1" required>
</div>
<button class="btn btn-primary">Pridať grade</button>
</form>
</div>
<div class="col-md-6">
<form method="post" class="border rounded p-3">
<input type="hidden" name="form" value="style">
<h3 class="h5">Nový style</h3>
<div class="mb-2">
<label class="form-label" for="style-name">Style</label>
<input class="form-control" id="style-name" name="name" required>
</div>
<button class="btn btn-primary">Pridať style</button>
</form>
</div>
</div>
<h2>Obsah tables</h2>
<p>Každá table tak, ako je v databáze: s id, foreign keys a dvojicami v pivot table. Nad tabuľkou je SQL, ktoré ju vypísalo. Record v lookup table má odkaz Upraviť a button Zmazať. Novú cestu pridáš v <a href="add-route.php">add-route.php</a>.</p>
<?php $editable = ['grades' => 'grade', 'styles' => 'style']; ?> <!-- lookup tables a slovo do názvu file: edit-grade.php, delete-grade.php -->
<?php foreach (['grades', 'styles', 'routes', 'route_styles'] as $table): ?> <!-- názvy tables sú v skripte, nie od používateľa -->
<?php
$sql = 'SELECT * FROM ' . $table; // preto stačí query
$rows = $pdo->query($sql)->fetchAll();
?>
<h3 class="h5 mt-4"><?= $table ?></h3>
<pre class="small"><?= $sql ?></pre>
<?php if ($rows): ?> <!-- prázdny array = table bez records -->
<table class="table table-sm table-striped">
<thead>
<tr>
<?php foreach (array_keys($rows[0]) as $column): ?> <!-- názvy columns = keys prvého record -->
<th><?= $column ?></th>
<?php endforeach; ?>
<?php if (isset($editable[$table])): ?> <!-- len lookup tables majú column s akciami -->
<th>akcia</th>
<?php endif; ?>
</tr>
</thead>
<tbody>
<?php foreach ($rows as $row): ?> <!-- každý record -->
<tr>
<?php foreach ($row as $value): ?> <!-- každá column v record -->
<td><?= htmlspecialchars($value ?? '') ?></td> <!-- ?? '': column bez hodnoty je NULL, htmlspecialchars chce text -->
<?php endforeach; ?>
<?php if (isset($editable[$table])): ?>
<td>
<a class="btn btn-outline-primary btn-sm" href="edit-<?= $editable[$table] ?>.php?id=<?= $row['id'] ?>">Upraviť</a> <!-- id v URL -->
<form method="post" action="delete-<?= $editable[$table] ?>.php"> <!-- mazanie cez POST -->
<input type="hidden" name="id" value="<?= $row['id'] ?>"> <!-- id v hidden input -->
<button class="btn btn-outline-danger btn-sm">Zmazať</button>
</form>
</td>
<?php endif; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php else: ?>
<p class="text-muted">Table je prázdna.</p>
<?php endif; ?>
<?php endforeach; ?>
Databáza
(formuláre na nový record a ostatné tables sú na stránke tiež, v náhľade sú len lookup tables)
grades
SELECT * FROM grades
| id | name | value | akcia |
|---|---|---|---|
| 1 | 5a | 5.0 | Upraviť Zmazať |
| 2 | 6a | 6.0 | Upraviť Zmazať |
| 3 | 6b | 6.3 | Upraviť Zmazať |
styles
SELECT * FROM styles
| id | name | akcia |
|---|---|---|
| 3 | boulder | Upraviť Zmazať |
| 2 | lead | Upraviť Zmazať |
| 1 | toprope | Upraviť Zmazať |
Takto to vyzerá v prehliadači: otvorená adresa je data.php. V tabuľkách grades a styles má každý record odkaz Upraviť a button Zmazať. Odkaz Upraviť pri grade 6b má adresu edit-grade.php?id=3. Button Zmazať pri grade 6b pošle POST request na delete-grade.php s id 3. Tabuľky routes a route_styles column akcia nemajú.
Čo robí ktorý riadok:
$editable = ['grades' => 'grade', 'styles' => 'style']: key je názov lookup table, value je slovo do názvu file,isset($editable[$table]):true, keď je vypisovaná table v array$editable,href="edit-<?= $editable[$table] ?>.php?id=<?= $row['id'] ?>": pre tablegradesa record sid3 vznikneedit-grade.php?id=3.
Vo svojej aplikácii. V $editable uveď svoje lookup tables a slovo do názvu file, napr. ['genres' => 'genre', 'tags' => 'tag'].
Ukážka 4: edit-grade.php (lookup table), UPDATE
<?php
// ROLA: lookup table grades, formulár na úpravu jedného record (file stránky)
// CRUD: Update
// OTVÁRA SA: z data.php, odkaz Upraviť v table grades: edit-grade.php?id=3
// ROBÍ: pripojí databázu, nastaví titulok a content file content/edit-grade.php
// VO SVOJEJ APLIKÁCII: edit- a názov lookup table v jednotnom čísle, napr. edit-genre.php
require 'db.php'; // pripojenie: content file bude mať $pdo
$title = 'Upraviť grade'; // titulok: vypíše ho template.php v <title> a v <h1>
$active = 'data'; // ktorá položka menu je zvýraznená
$content = 'content/edit-grade.php'; // content file tejto stránky
include 'template.php'; // template.php vypíše HTML a vloží content file
<?php
// ROLA: lookup table grades, formulár na úpravu jedného record (content file)
// CRUD: Update
// OTVÁRA SA: vkladá ho template.php, keď sa otvorí edit-grade.php?id=3
// ROBÍ: po odoslaní formulára vykoná UPDATE a vypíše správu; potom načíta record a vypíše formulár s jeho hodnotami
// VO SVOJEJ APLIKÁCII: zmeň názov table, columns a inputs podľa svojej lookup table
$id = $_GET['id'] ?? ''; // id z URL: edit-grade.php?id=3
$message = ''; // správa pre používateľa
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // formulár bol odoslaný
$name = $_POST['name']; // najprv všetko z $_POST do premenných
$value = $_POST['value'];
if ($name === '' || $value === '') {
$message = 'Vyplň grade aj hodnotu.';
} else {
$stmt = $pdo->prepare('SELECT id FROM grades WHERE name = ? AND id <> ?'); // má ten istý name iný record?
$stmt->execute([$name, $id]);
if ($stmt->fetch()) { // fetch vráti record alebo false
$message = 'Grade ' . $name . ' už existuje.';
} else {
$stmt = $pdo->prepare('UPDATE grades SET name = ?, value = ? WHERE id = ?');
$stmt->execute([$name, $value, $id]); // id na konci: posledný ? patrí k WHERE
$message = 'Záznam bol upravený.';
}
}
}
$stmt = $pdo->prepare('SELECT * FROM grades WHERE id = ?'); // record na úpravu, po UPDATE už s novými hodnotami
$stmt->execute([$id]);
$grade = $stmt->fetch();
if (!$grade) { // id v URL chýba alebo taký record nie je
echo '<p>Grade sa nenašiel.</p>';
return; // ďalej sa nič nevypíše
}
?>
<?php if ($message !== ''): ?>
<div class="alert alert-info"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>
<form method="post" class="row g-3"> <!-- bez action: request ide na tú istú adresu aj s ?id=3 -->
<div class="col-md-6">
<label class="form-label" for="name">Grade</label>
<input class="form-control" id="name" name="name" value="<?= htmlspecialchars($grade['name']) ?>" required> <!-- value: hodnota z databázy -->
</div>
<div class="col-md-6">
<label class="form-label" for="value">Hodnota na porovnávanie</label>
<input class="form-control" id="value" name="value" type="number" step="0.1" value="<?= $grade['value'] ?>" required>
</div>
<div class="col-12">
<button class="btn btn-primary">Uložiť zmeny</button>
<a class="btn btn-outline-secondary" href="data.php">Späť</a>
</div>
</form>
Upraviť grade
Takto to vyzerá v prehliadači: po kliknutí na Upraviť pri grade 6b v data.php sa otvorí adresa edit-grade.php?id=3. Formulár má v input hodnoty z databázy: 6b a 6.3.
Upraviť grade
Po zmene hodnôt na 6b+ a 6.4 a kliknutí na Uložiť zmeny zostáva adresa edit-grade.php?id=3. Nad formulárom je správa „Záznam bol upravený.” a formulár ukazuje nové hodnoty. Vykonal sa UPDATE: UPDATE grades SET name = '6b+', value = 6.4 WHERE id = 3. Keď sa do input Grade napíše 5a, nad formulárom je správa „Grade 5a už existuje.” a UPDATE sa nevykoná. Adresa edit-grade.php?id=99 vypíše „Grade sa nenašiel.”
Vo svojej aplikácii. File stránky edit-LOOKUP.php a content file content/edit-LOOKUP.php pre každú lookup table. Zmeň názov table, columns v SET, inputs vo formulári a texty správ. Vo vzore je rovnako spravený edit-style.php pre table styles.
Ukážka 5: delete-grade.php (lookup table), DELETE s kontrolou
<?php
// ROLA: lookup table grades, zmazanie jedného record (file bez stránky, nemá content file)
// CRUD: Delete
// OTVÁRA SA: z data.php, button Zmazať v table grades (formulár POST s hidden input id)
// ROBÍ: zistí, či je grade použitý v routes; ak nie, vykoná DELETE; potom redirect na data.php so správou
// VO SVOJEJ APLIKÁCII: delete- a názov lookup table v jednotnom čísle, napr. delete-genre.php
require 'db.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { // file otvorený cez adresu (GET): nič sa nemaže
header('Location: data.php'); // header pošle prehliadaču adresu, na ktorú má prejsť
exit; // exit ukončí skript, ďalej sa nič nevykoná
}
$id = $_POST['id']; // id z hidden input vo formulári s buttonom Zmazať
$stmt = $pdo->prepare('SELECT COUNT(*) AS routes_count FROM routes WHERE grade_id = ?');
$stmt->execute([$id]);
$row = $stmt->fetch(); // jeden record s počtom
if ($row['routes_count'] > 0) { // record je použitý: DELETE by databáza odmietla (RESTRICT)
header('Location: data.php?msg=used');
exit;
}
$stmt = $pdo->prepare('DELETE FROM grades WHERE id = ?');
$stmt->execute([$id]); // vykoná sa DELETE
header('Location: data.php?msg=deleted'); // redirect: prehliadač otvorí data.php so správou
exit;
Databáza
grades
SELECT * FROM grades
| id | name | value | akcia |
|---|---|---|---|
| 1 | 5a | 5.0 | Upraviť Zmazať |
| 2 | 6a | 6.0 | Upraviť Zmazať |
| 3 | 6b | 6.3 | Upraviť Zmazať |
Takto to vyzerá v prehliadači: po kliknutí na Zmazať pri grade 5a v data.php sa otvorí adresa data.php?msg=used. Pod titulkom je správa „Záznam sa nedá zmazať, je použitý.” a grade 5a v tabuľke zostal. SELECT vrátil routes_count 2, DELETE sa nevykonal.
Databáza
styles
SELECT * FROM styles
| id | name | akcia |
|---|---|---|
| 2 | lead | Upraviť Zmazať |
| 1 | toprope | Upraviť Zmazať |
Na dátach zo seed.sql má každý grade aspoň jednu cestu. Úspešný DELETE ukáže vo vzore table styles: style boulder nie je v žiadnej dvojici. Po kliknutí na Zmazať pri style boulder v data.php sa vykoná DELETE FROM styles WHERE id = 3 v delete-style.php a otvorí sa adresa data.php?msg=deleted. Pod titulkom je správa „Záznam bol zmazaný.” a v tabuľke styles zostali lead a toprope.
Vo svojej aplikácii. File delete-LOOKUP.php pre každú lookup table, bez content file. Zmeň názov table v DELETE a SELECT s kontrolou: pre lookup table s reláciou 1:N sa počítajú records main entity (WHERE grade_id = ?), pre lookup table s reláciou M:N dvojice v pivot table (WHERE style_id = ?).
Ukážka 6: detail.php (main entity), odkaz Upraviť a button Zmazať
content/detail.php z cv07 vypisuje jednu cestu. V cv08 pribudol v SELECT column routes.id a pod výpisom odkaz Upraviť a button Zmazať.
<?php
// ROLA: main entity, detail jedného record (file stránky)
// CRUD: Read
// OTVÁRA SA: z routes.php, odkaz detail: detail.php?id=2
// ROBÍ: pripojí databázu, nastaví titulok a content file content/detail.php
// VO SVOJEJ APLIKÁCII: názov detail.php zostáva, zmeň $title a $active
require 'db.php'; // pripojenie: content file bude mať $pdo
$title = 'Detail cesty'; // titulok: vypíše ho template.php v <title> a v <h1>
$active = 'routes'; // ktorá položka menu je zvýraznená
$content = 'content/detail.php'; // content file tejto stránky
include 'template.php'; // template.php vypíše HTML a vloží content file
<?php
// ROLA: main entity, detail jedného record (content file)
// CRUD: Read
// OTVÁRA SA: vkladá ho template.php, keď sa otvorí detail.php?id=2
// ROBÍ: vypíše cestu s grade a styles; má odkaz Upraviť (edit-route.php?id=2) a button Zmazať (delete-route.php)
// VO SVOJEJ APLIKÁCII: zmeň SQL a výpis podľa svojej main entity
$id = $_GET['id'] ?? ''; // id z URL: detail.php?id=2
// ZLE: hodnota z URL vlepená priamo do SQL (nechané v komentári len ako ukážka, nikdy nepoužívať)
// $stmt = $pdo->query("SELECT routes.name, holds, grades.name AS grade, since, note FROM routes
// JOIN grades ON routes.grade_id = grades.id WHERE routes.id = $id");
// DOBRE: hodnota z URL cez prepare
$stmt = $pdo->prepare('SELECT routes.id, routes.name, holds, grades.name AS grade, since, note
FROM routes JOIN grades ON routes.grade_id = grades.id
WHERE routes.id = ?');
$stmt->execute([$id]);
$route = $stmt->fetch(); // jeden record alebo false
if (!$route) { // id neexistuje alebo nie je číslo
echo '<p>Cesta sa nenašla.</p>';
return; // ďalej sa nič nevypíše
}
$stmt = $pdo->prepare('SELECT styles.name FROM route_styles
JOIN styles ON styles.id = route_styles.style_id
WHERE route_styles.route_id = ?'); // styles tejto cesty cez pivot table
$stmt->execute([$id]);
$styles = $stmt->fetchAll();
?>
<h2><?= htmlspecialchars($route['name']) ?></h2>
<p>Grade <?= htmlspecialchars($route['grade']) ?>, chyty <?= htmlspecialchars($route['holds']) ?>, postavená <?= $route['since'] ?></p>
<p><?= htmlspecialchars($route['note'] ?? '') ?></p> <!-- note je nepovinná, môže byť NULL -->
<p>Styles:
<?php foreach ($styles as $style): ?>
<span class="badge text-bg-secondary"><?= htmlspecialchars($style['name']) ?></span>
<?php endforeach; ?>
</p>
<a class="btn btn-outline-primary btn-sm" href="edit-route.php?id=<?= $route['id'] ?>">Upraviť</a> <!-- id v URL -->
<form method="post" action="delete-route.php" class="d-inline"> <!-- mazanie cez POST -->
<input type="hidden" name="id" value="<?= $route['id'] ?>"> <!-- id v hidden input -->
<button class="btn btn-outline-danger btn-sm">Zmazať</button>
</form>
<a class="btn btn-outline-secondary btn-sm" href="routes.php">Späť</a>
Detail cesty
Modrý previs
Grade 6a, chyty modré, postavená 2026-09-21
Previs s dobrými chytmi.
Styles: toprope lead
Upraviť Zmazať Späť
Takto to vyzerá v prehliadači: po kliknutí na detail pri ceste Modrý previs v routes.php sa otvorí adresa detail.php?id=2. Odkaz Upraviť má adresu edit-route.php?id=2. Button Zmazať pošle POST request na delete-route.php s id 2.
Vo svojej aplikácii. Do content/detail.php doplň odkaz na edit-ENTITY.php?id=... a formulár s action="delete-ENTITY.php". SELECT musí vracať id main entity.
Ukážka 7: edit-route.php (main entity), UPDATE s pivot table
<?php
// ROLA: main entity, formulár na úpravu jedného record (file stránky)
// CRUD: Update
// OTVÁRA SA: z detail.php, odkaz Upraviť: edit-route.php?id=2
// ROBÍ: pripojí databázu, nastaví titulok a content file content/edit-route.php
// VO SVOJEJ APLIKÁCII: edit- a názov main entity v jednotnom čísle, napr. edit-book.php
require 'db.php'; // pripojenie: content file bude mať $pdo
$title = 'Upraviť cestu'; // titulok: vypíše ho template.php v <title> a v <h1>
$active = 'routes'; // ktorá položka menu je zvýraznená
$content = 'content/edit-route.php'; // content file tejto stránky
include 'template.php'; // template.php vypíše HTML a vloží content file
<?php
// ROLA: main entity, formulár na úpravu jedného record (content file)
// CRUD: Update
// OTVÁRA SA: vkladá ho template.php, keď sa otvorí edit-route.php?id=2
// ROBÍ: po odoslaní formulára vykoná UPDATE v routes a nanovo zapíše dvojice do pivot table; potom vypíše formulár s hodnotami z databázy
// VO SVOJEJ APLIKÁCII: zmeň názvy tables, columns a inputs; formulár je ten istý ako v add-ENTITY.php, len s vyplnenými hodnotami
$id = $_GET['id'] ?? ''; // id z URL: edit-route.php?id=2
$message = '';
$stmt = $pdo->prepare('SELECT id FROM routes WHERE id = ?'); // existuje cesta s týmto id?
$stmt->execute([$id]);
if (!$stmt->fetch()) { // bez cesty sa nedá upravovať ani zapisovať dvojice
echo '<p>Cesta sa nenašla.</p>';
return;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // formulár bol odoslaný
$name = $_POST['name'];
$holds = $_POST['holds'];
$gradeId = $_POST['grade_id']; // id zo selectu
$since = $_POST['since'];
$note = $_POST['note'];
$styleIds = $_POST['style'] ?? []; // array zaškrtnutých id; keď nič, prázdny array
if ($name === '' || $holds === '' || $gradeId === '' || $since === '') {
$message = 'Vyplň názov, chyty, grade a dátum.';
} else {
$stmt = $pdo->prepare('UPDATE routes SET name = ?, holds = ?, grade_id = ?, since = ?, note = ? WHERE id = ?');
$stmt->execute([$name, $holds, $gradeId, $since, $note, $id]); // UPDATE main entity; id na konci patrí k WHERE
$stmt = $pdo->prepare('DELETE FROM route_styles WHERE route_id = ?');
$stmt->execute([$id]); // pivot table: zmažú sa všetky dvojice tejto cesty
$stmt = $pdo->prepare('INSERT INTO route_styles (route_id, style_id) VALUES (?, ?)'); // prepare raz
foreach ($styleIds as $styleId) { // a zapíšu sa nanovo podľa zaškrtnutých checkboxov
$stmt->execute([$id, $styleId]);
}
$message = 'Záznam bol upravený.';
}
}
$stmt = $pdo->prepare('SELECT * FROM routes WHERE id = ?'); // cesta na úpravu, po UPDATE už s novými hodnotami
$stmt->execute([$id]);
$route = $stmt->fetch();
$stmt = $pdo->prepare('SELECT style_id FROM route_styles WHERE route_id = ?'); // dvojice tejto cesty
$stmt->execute([$id]);
$routeStyleIds = array_column($stmt->fetchAll(), 'style_id'); // array_column vyberie jednu column: [1, 2]
$grades = $pdo->query('SELECT id, name FROM grades ORDER BY value')->fetchAll(); // pre select
$styles = $pdo->query('SELECT id, name FROM styles ORDER BY name')->fetchAll(); // pre checkboxy
?>
<?php if ($message !== ''): ?>
<div class="alert alert-info"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>
<form method="post" class="row g-3"> <!-- bez action: request ide na tú istú adresu aj s ?id=2 -->
<div class="col-md-6">
<label class="form-label" for="name">Názov cesty</label>
<input class="form-control" id="name" name="name" value="<?= htmlspecialchars($route['name']) ?>" required>
</div>
<div class="col-md-6">
<label class="form-label" for="holds">Farba chytov</label>
<input class="form-control" id="holds" name="holds" value="<?= htmlspecialchars($route['holds']) ?>" required>
</div>
<div class="col-md-6">
<label class="form-label" for="grade_id">Grade</label>
<select class="form-select" id="grade_id" name="grade_id" required>
<?php foreach ($grades as $grade): ?>
<option value="<?= $grade['id'] ?>" <?= $grade['id'] == $route['grade_id'] ? 'selected' : '' ?>><?= htmlspecialchars($grade['name']) ?></option> <!-- selected: grade tejto cesty -->
<?php endforeach; ?>
</select>
</div>
<div class="col-md-6">
<label class="form-label" for="since">Postavená od</label>
<input class="form-control" id="since" name="since" type="date" value="<?= $route['since'] ?>" required>
</div>
<div class="col-12">
<label class="form-label" for="note">Poznámka</label>
<textarea class="form-control" id="note" name="note" rows="2"><?= htmlspecialchars($route['note'] ?? '') ?></textarea> <!-- textarea nemá value, text je medzi tagmi -->
</div>
<div class="col-12">
<span class="form-label d-block">Styles</span>
<?php foreach ($styles as $style): ?>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="style-<?= $style['id'] ?>" name="style[]" value="<?= $style['id'] ?>" <?= in_array($style['id'], $routeStyleIds) ? 'checked' : '' ?>> <!-- in_array: je id medzi dvojicami cesty? -->
<label class="form-check-label" for="style-<?= $style['id'] ?>"><?= htmlspecialchars($style['name']) ?></label>
</div>
<?php endforeach; ?>
</div>
<div class="col-12">
<button class="btn btn-primary">Uložiť zmeny</button>
<a class="btn btn-outline-secondary" href="detail.php?id=<?= $route['id'] ?>">Späť</a>
</div>
</form>
Upraviť cestu
Takto to vyzerá v prehliadači: po kliknutí na Upraviť v detail.php?id=2 sa otvorí adresa edit-route.php?id=2. Formulár je ten istý ako v add-route.php, s hodnotami cesty Modrý previs. V select je vybraný grade 6a. Zaškrtnuté sú lead a toprope, lebo $routeStyleIds je [1, 2].
Upraviť cestu
Po výbere grade 6b, odškrtnutí lead a kliknutí na Uložiť zmeny zostáva adresa edit-route.php?id=2. Nad formulárom je správa „Záznam bol upravený.” Vykonal sa UPDATE v routes (grade_id je 3), DELETE dvojíc (2, 1) a (2, 2) v route_styles a INSERT dvojice (2, 1). V data.php má table route_styles dvojice (1, 1) a (2, 1).
Vo svojej aplikácii. File stránky edit-ENTITY.php a content file content/edit-ENTITY.php. Formulár skopíruj z content/add-ENTITY.php a doplň hodnoty z databázy do value, selected, checked a medzi tagy textarea. Zmeň názvy tables a columns v UPDATE, DELETE, INSERT a SELECT.
Ukážka 8: delete-route.php (main entity), DELETE
<?php
// ROLA: main entity, zmazanie jedného record (file bez stránky, nemá content file)
// CRUD: Delete
// OTVÁRA SA: z detail.php, button Zmazať (formulár POST s hidden input id)
// ROBÍ: vykoná DELETE v routes; potom redirect na routes.php so správou
// VO SVOJEJ APLIKÁCII: delete- a názov main entity v jednotnom čísle, napr. delete-book.php
require 'db.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { // file otvorený cez adresu (GET): nič sa nemaže
header('Location: routes.php'); // header pošle prehliadaču adresu, na ktorú má prejsť
exit; // exit ukončí skript, ďalej sa nič nevykoná
}
$id = $_POST['id']; // id z hidden input vo formulári s buttonom Zmazať
// dvojice v pivot table route_styles zmaže databáza (ON DELETE CASCADE)
$stmt = $pdo->prepare('DELETE FROM routes WHERE id = ?');
$stmt->execute([$id]); // vykoná sa DELETE
header('Location: routes.php?msg=deleted'); // redirect: prehliadač otvorí routes.php so správou
exit;
Cesty
Ciest: 3
Zelená platňa 5a
Chyty: zelené, postavená 2026-10-19
detailČervená platňa 6b
Chyty: červené, postavená 2026-10-05
detailŽltá hrana 5a
Chyty: žlté, postavená 2026-09-14
detailTakto to vyzerá v prehliadači: po kliknutí na Zmazať v detail.php?id=2 sa vykoná DELETE FROM routes WHERE id = 2 a otvorí sa adresa routes.php?msg=deleted. Pod titulkom Cesty je správa „Záznam bol zmazaný.” a v zozname sú Zelená platňa, Červená platňa a Žltá hrana. Dvojice (2, 1) a (2, 2) zmazala z route_styles databáza (ON DELETE CASCADE), v pivot table zostala dvojica (1, 1).
Vo svojej aplikácii. File delete-ENTITY.php bez content file. Zmeň názov table a adresu v header() na ENTITY.php. Keď pivot table v schema.sql nemá ON DELETE CASCADE, pred DELETE z main entity patrí DELETE FROM pivot_table WHERE ... = ?.
Ukážka 9: prompty
Prompt U pomáha s unify.txt. Prikladá sa unify.txt, sql/schema.sql a tabuľka rolí z časti Z čoho sa aplikácia skladá.
Prikladám unify.txt z predmetu Technológie internetu, sql/schema.sql a tabuľku rolí s pravidlom názvov files. V unify.txt skontroluj riadky entity a lookup podľa schema.sql. Každý otáznik nahraď novým názvom file podľa tabuľky rolí alebo slovom zmazat. Riadky bez otáznika nemeň. Vráť celý unify.txt a pod ním pri každom zmenenom riadku jednou vetou, akú rolu má file a prečo.
Prompt A, UPDATE a DELETE pre lookup table. Prikladá sa sql/schema.sql, web/template.php, web/content/data.php a files, ktoré vytvoril unify.py: web/edit-LOOKUP.php, web/content/edit-LOOKUP.php, web/delete-LOOKUP.php.
PHP aplikácia: stránku tvorí file stránky web/X.php ($title, $active, $content, include 'template.php') a content file web/content/X.php. $pdo je pripravené v db.php. Pre lookup table LOOKUP zo schema.sql doplň priložené files, komentár s rolou na začiatku každého file nechaj. 1. content/data.php: v tabuľke lookup table pridaj column akcia s odkazom Upraviť (edit-LOOKUP.php?id=...) a formulárom method POST action delete-LOOKUP.php s hidden input id a buttonom Zmazať. 2. content/edit-LOOKUP.php: id z $_GET; po POST hodnoty z $_POST do premenných, kontrola povinných, SELECT ... WHERE name = ? AND id <> ? s fetch na kontrolu duplicity, UPDATE ... WHERE id = ? cez prepare a execute, správa do $message; potom SELECT record podľa id, keď neexistuje správa a return; správa v alert a Bootstrap formulár method POST bez action s hodnotami z databázy vo value. 3. delete-LOOKUP.php bez content file a bez template: require 'db.php'; keď request nie je POST, header('Location: data.php') a exit; id z $_POST; SELECT COUNT(*) na table, ktorá na LOOKUP ukazuje cez foreign key; keď je počet väčší ako 0, redirect na data.php?msg=used; inak DELETE cez prepare a execute a redirect na data.php?msg=deleted; po každom header exit. 4. template.php: na začiatok array $messages s keys deleted a used, pod <h1> výpis správy podľa $_GET['msg'] v alert. Bez funkcií a tried, komentár pri každom riadku po slovensky. Text správ nechaj ako // DOPLŇ.
Prompt B, UPDATE a DELETE pre main entity. Prikladá sa sql/schema.sql, web/content/add-ENTITY.php, web/content/detail.php a files, ktoré vytvoril unify.py: web/edit-ENTITY.php, web/content/edit-ENTITY.php, web/delete-ENTITY.php.
Pre tú istú aplikáciu doplň priložené files pre main entity ENTITY, komentár s rolou na začiatku každého file nechaj. 1. content/detail.php: SELECT nech vracia aj id; pod výpis odkaz Upraviť (edit-ENTITY.php?id=...) a formulár method POST action delete-ENTITY.php s hidden input id a buttonom Zmazať. 2. content/edit-ENTITY.php: formulár z priloženého content/add-ENTITY.php zachovaj, zmeň len to, čo píšem. id z $_GET; najprv SELECT, či record existuje, inak správa a return. Po POST: hodnoty z $_POST do premenných, kontrola povinných, UPDATE ... WHERE id = ?, potom DELETE dvojíc tohto record v pivot table a INSERT zaškrtnutých vo foreach cez jeden pripravený príkaz, správa do $message. Potom SELECT record a SELECT jeho dvojíc, array_column na array id. Vo formulári hodnoty z databázy: value pri input, text medzi tagmi textarea, selected pri option, checked cez in_array pri checkbox. 3. delete-ENTITY.php bez content file a bez template: require 'db.php'; keď request nie je POST, redirect na ENTITY.php; id z $_POST; DELETE cez prepare a execute; header('Location: ENTITY.php?msg=deleted') a exit. Bez funkcií a tried, komentár pri každom riadku po slovensky. Validačné pravidlá nechaj ako // DOPLŇ.
Prečo sú prompty napísané práve takto:
- priložené files namiesto opisu: AI vidí presné názvy tables, columns a files a dopĺňa do nich,
- „komentár s rolou nechaj”: mapa aplikácie v
README.mda komentáre vo files zostanú rovnaké, - „formulár zachovaj, zmeň len to, čo píšem” bráni AI prerobiť formulár z cv07,
- „bez content file a bez template” pri delete: AI nevloží do file HTML a
header()bude fungovať, - „po každom header exit”: bez
exitby sa po kontrole vykonal aj DELETE, // DOPLŇnecháva texty správ a validačné pravidlá na autorovi aplikácie,- prompt U mení len riadky s otáznikom: premenovanie robí
unify.py, AI len navrhne názvy.
The examples are files of the climbing wall application from sample cv08. Every file is complete, with the comment about its role at the beginning. Below the code is a preview of the page in the browser with the address that opens. Every example starts from the data in seed.sql: grades 5a, 6a, 6b, styles toprope, lead, boulder, routes Žltá hrana, Modrý previs, Červená platňa, Zelená platňa. Comments in the code and texts in the application are in Slovak.
Example 1: unification of the sample
Before unification the sample is the state from cv07 with leftovers from cv05: form.php, content/register.php, the folder practice/ and content/home.php, whose name differs from the page file index.php.
cd cv08
python3 unify.py --init
The script creates unify.txt. It determined the tables from sql/schema.sql. For files known from the labs it proposed a new name or zmazat:
# unify.txt: plán unifikácie. Riadky so znakom # na začiatku sú komentáre.
#
# 1. Skontroluj tables. Za názvom table je slovo do názvu file (názov v jednotnom čísle).
# Z entity: routes route vzniknú názvy routes.php, add-route.php, edit-route.php, delete-route.php.
entity: routes route
lookup: grades grade
lookup: styles style
# 2. Pri každom file napíš za šípku nový názov podľa pravidla. Namiesto názvu môže byť: zmazat
# Otáznik: script nový názov neurčil. Nahraď ho názvom zo zoznamu na konci alebo slovom zmazat.
# Cesty sú od priečinka web/.
add-route.php -> add-route.php
contact.php -> contact.php
data.php -> data.php
db.php -> db.php
detail.php -> detail.php
form.php -> zmazat
index.php -> index.php
routes.php -> routes.php
stats.php -> stats.php
template.php -> template.php
content/add-route.php -> content/add-route.php
content/contact.php -> content/contact.php
content/data.php -> content/data.php
content/detail.php -> content/detail.php
content/home.php -> content/index.php
content/register.php -> zmazat
content/routes.php -> content/routes.php
content/stats.php -> content/stats.php
practice/loop.php -> zmazat
# Názvy podľa pravidla, ktoré zatiaľ nemá žiadny file. Čo zostane voľné, vytvorí script ako nový file.
# edit-route.php main entity routes, formulár na úpravu jedného record (file stránky)
# content/edit-route.php main entity routes, formulár na úpravu jedného record (content file)
# delete-route.php main entity routes, zmazanie jedného record (file bez stránky)
# edit-grade.php lookup table grades, formulár na úpravu jedného record (file stránky)
# content/edit-grade.php lookup table grades, formulár na úpravu jedného record (content file)
# delete-grade.php lookup table grades, zmazanie jedného record (file bez stránky)
# edit-style.php lookup table styles, formulár na úpravu jedného record (file stránky)
# content/edit-style.php lookup table styles, formulár na úpravu jedného record (content file)
# delete-style.php lookup table styles, zmazanie jedného record (file bez stránky)
python3 unify.py prints the plan. No files change:
Main entity: routes (slovo do názvu file: route)
Lookup tables: grades (grade), styles (style)
Premenovať:
content/home.php -> content/index.php
Zmazať:
form.php
content/register.php
practice/loop.php
Vytvoriť (v aplikácii chýba):
edit-route.php main entity routes, formulár na úpravu jedného record (file stránky)
content/edit-route.php main entity routes, formulár na úpravu jedného record (content file)
delete-route.php main entity routes, zmazanie jedného record (file bez stránky)
edit-grade.php lookup table grades, formulár na úpravu jedného record (file stránky)
content/edit-grade.php lookup table grades, formulár na úpravu jedného record (content file)
delete-grade.php lookup table grades, zmazanie jedného record (file bez stránky)
edit-style.php lookup table styles, formulár na úpravu jedného record (file stránky)
content/edit-style.php lookup table styles, formulár na úpravu jedného record (content file)
delete-style.php lookup table styles, zmazanie jedného record (file bez stránky)
Zatiaľ sa nič nezmenilo. Ak plán sedí, spusti: python3 unify.py --run
python3 unify.py --run carries out the plan:
Zmeny:
premenovaný: content/home.php -> content/index.php
zmazaný: form.php
zmazaný: content/register.php
zmazaný: practice/loop.php
odkaz opravený v index.php: content/home.php -> content/index.php
vytvorený: edit-route.php
vytvorený: content/edit-route.php
vytvorený: delete-route.php
vytvorený: edit-grade.php
vytvorený: content/edit-grade.php
vytvorený: delete-grade.php
vytvorený: edit-style.php
vytvorený: content/edit-style.php
vytvorený: delete-style.php
komentár s rolou doplnený: add-route.php
komentár s rolou doplnený: contact.php
komentár s rolou doplnený: data.php
komentár s rolou doplnený: db.php
komentár s rolou doplnený: detail.php
komentár s rolou doplnený: index.php
komentár s rolou doplnený: routes.php
komentár s rolou doplnený: stats.php
komentár s rolou doplnený: template.php
komentár s rolou doplnený: content/add-route.php
komentár s rolou doplnený: content/contact.php
komentár s rolou doplnený: content/data.php
komentár s rolou doplnený: content/detail.php
komentár s rolou doplnený: content/index.php
komentár s rolou doplnený: content/routes.php
komentár s rolou doplnený: content/stats.php
mapa aplikácie zapísaná do README.md
Kontrola: každý odkaz vedie na existujúci file, každá stránka má content file.
Ďalej: otvor aplikáciu v prehliadači, prejdi každú položku menu a potom:
git add -A && git commit -m "unifikácia názvov files"
The map of the application that the script wrote into README.md:
| file | rola | CRUD |
|---|---|---|
web/db.php |
pripojenie k databáze, spoločný file | žiadna |
web/template.php |
template, spoločný file každej stránky | žiadna |
web/index.php |
úvodná stránka (file stránky) | žiadna |
web/content/index.php |
úvodná stránka (content file) | žiadna |
web/contact.php |
stránka s kontaktom (file stránky) | žiadna |
web/content/contact.php |
stránka s kontaktom (content file) | žiadna |
web/routes.php |
main entity routes, zoznam (file stránky) | Read |
web/content/routes.php |
main entity routes, zoznam (content file) | Read |
web/detail.php |
main entity routes, detail jedného record (file stránky) | Read |
web/content/detail.php |
main entity routes, detail jedného record (content file) | Read |
web/add-route.php |
main entity routes, formulár na nový record (file stránky) | Create |
web/content/add-route.php |
main entity routes, formulár na nový record (content file) | Create |
web/edit-route.php |
main entity routes, formulár na úpravu jedného record (file stránky) | Update |
web/content/edit-route.php |
main entity routes, formulár na úpravu jedného record (content file) | Update |
web/delete-route.php |
main entity routes, zmazanie jedného record (file bez stránky) | Delete |
web/data.php |
lookup tables, formuláre na nový record a výpis tables (file stránky) | Create, Read |
web/content/data.php |
lookup tables, formuláre na nový record a výpis tables (content file) | Create, Read |
web/edit-grade.php |
lookup table grades, formulár na úpravu jedného record (file stránky) | Update |
web/content/edit-grade.php |
lookup table grades, formulár na úpravu jedného record (content file) | Update |
web/delete-grade.php |
lookup table grades, zmazanie jedného record (file bez stránky) | Delete |
web/edit-style.php |
lookup table styles, formulár na úpravu jedného record (file stránky) | Update |
web/content/edit-style.php |
lookup table styles, formulár na úpravu jedného record (content file) | Update |
web/delete-style.php |
lookup table styles, zmazanie jedného record (file bez stránky) | Delete |
web/stats.php |
prehľad, výpisy s JOIN a GROUP BY (file stránky) | Read |
web/content/stats.php |
prehľad, výpisy s JOIN a GROUP BY (content file) | Read |
A file created by the script has the comment with the role and a place to complete. The application works with it right away; for now the button Zmazať only returns the browser to data.php:
<?php
// ROLA: lookup table grades, zmazanie jedného record (file bez stránky)
// CRUD: Delete
// OTVÁRA SA: z data.php, button Zmazať (formulár POST s hidden input id)
// DOPLŇ v úlohe 9.6: kontrola, DELETE, redirect so správou
header('Location: data.php'); // zatiaľ len redirect späť
exit;
In your own application. In unify.txt check the lines entity and lookup: the name of the table and the word used in file names. Replace every question mark with a name from the table of roles or with the word zmazat. A file that is not in the table of roles but is used by the application keeps its name.
Example 2: template.php with the message after a redirect
template.php is the shared file of every page. Compared with cv07 it has the array $messages at the beginning and the message printed below <h1>.
<?php
// ROLA: template, spoločný file každej stránky
// CRUD: žiadna
// OTVÁRA SA: v prehliadači sa neotvára; file stránky ho pripája cez include 'template.php'
// ROBÍ: vypíše <head>, menu, <h1> s titulkom, správu po redirect, content file a footer
// VO SVOJEJ APLIKÁCII: zmeň názov aplikácie a položky menu
$messages = [ // správy, ktoré sa zobrazia po redirect
'deleted' => 'Záznam bol zmazaný.',
'used' => 'Záznam sa nedá zmazať, je použitý.',
];
$msg = $_GET['msg'] ?? ''; // kľúč z URL, napr. data.php?msg=deleted
$text = $messages[$msg] ?? ''; // text k tomu kľúču; neznámy kľúč = prázdny text
?>
<!doctype html>
<html lang="sk">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= $title ?> | Lezecká stena</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<nav class="navbar navbar-expand-md bg-dark navbar-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="index.php">Lezecká stena</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#menu">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="menu">
<ul class="navbar-nav">
<li class="nav-item"><a class="nav-link <?= $active == 'index' ? 'active' : '' ?>" href="index.php">Domov</a></li>
<li class="nav-item"><a class="nav-link <?= $active == 'routes' ? 'active' : '' ?>" href="routes.php">Cesty</a></li>
<li class="nav-item"><a class="nav-link <?= $active == 'add-route' ? 'active' : '' ?>" href="add-route.php">Nová cesta</a></li>
<li class="nav-item"><a class="nav-link <?= $active == 'data' ? 'active' : '' ?>" href="data.php">Databáza</a></li>
<li class="nav-item"><a class="nav-link <?= $active == 'stats' ? 'active' : '' ?>" href="stats.php">Prehľad</a></li>
<li class="nav-item"><a class="nav-link <?= $active == 'contact' ? 'active' : '' ?>" href="contact.php">Kontakt</a></li>
</ul>
</div>
</div>
</nav>
<main class="container">
<h1><?= $title ?></h1>
<?php if ($text !== ''): ?>
<div class="alert alert-info"><?= $text ?></div>
<?php endif; ?>
<?php include $content; ?>
</main>
<footer class="bg-light mt-5">
<div class="container py-3">© <?= date('Y') ?> Lezecká stena</div>
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
Databáza
grades
SELECT * FROM grades
| id | name | value | akcia |
|---|---|---|---|
| 1 | 5a | 5.0 | Upraviť Zmazať |
| 2 | 6a | 6.0 | Upraviť Zmazať |
| 3 | 6b | 6.3 | Upraviť Zmazať |
What it looks like in the browser: the opened address is data.php?msg=used. Below the title Databáza is the message “Záznam sa nedá zmazať, je použitý.” The address data.php without msg and the address data.php?msg=abc show no message, because the array $messages has no key abc.
In your own application. Add the PHP block with $messages to the beginning of template.php and the message output below <h1>. The texts of the messages can stay the same.
Example 3: data.php (lookup tables), the link Upraviť and the button Zmazať
content/data.php from cv07 lists every table. In cv08 it has the array $editable with the lookup tables and the column akcia (action) in their tables. isset($array[$key]) returns true when the array has that key.
<?php
// ROLA: lookup tables, formuláre na nový record a výpis všetkých tables (file stránky)
// CRUD: Create, Read
// OTVÁRA SA: z menu, položka Databáza
// ROBÍ: pripojí databázu, nastaví titulok a content file content/data.php
// VO SVOJEJ APLIKÁCII: názov data.php zostáva
require 'db.php'; // pripojenie: content file bude mať $pdo
$title = 'Databáza'; // titulok: vypíše ho template.php v <title> a v <h1>
$active = 'data'; // ktorá položka menu je zvýraznená
$content = 'content/data.php'; // content file tejto stránky
include 'template.php'; // template.php vypíše HTML a vloží content file
<?php
// ROLA: lookup tables, formuláre na nový record a výpis všetkých tables (content file)
// CRUD: Create, Read
// OTVÁRA SA: vkladá ho template.php, keď sa otvorí data.php
// ROBÍ: po odoslaní formulára vykoná INSERT do lookup table; vypíše každú table; v lookup tables má každý record odkaz Upraviť a button Zmazať
// VO SVOJEJ APLIKÁCII: zmeň názvy tables a columns; v $editable uveď svoje lookup tables
$message = ''; // hláška pre používateľa
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['form'] ?? '') === 'grade') { // odoslaný formulár na grade
$name = $_POST['name']; // z input name="name", napr. 7a
$value = $_POST['value']; // z input name="value", napr. 7.0
if ($name === '' || $value === '') {
$message = 'Vyplň grade aj hodnotu.';
} else {
$stmt = $pdo->prepare('SELECT id FROM grades WHERE name = ?'); // existuje už taký grade?
$stmt->execute([$name]);
if ($stmt->fetch()) { // fetch vráti record, alebo false
$message = 'Grade ' . $name . ' už existuje.';
} else {
$stmt = $pdo->prepare('INSERT INTO grades (name, value) VALUES (?, ?)'); // SQL s dvoma otáznikmi
$stmt->execute([$name, $value]); // prvý ? = $name, druhý ? = $value
$message = 'Pridaný grade ' . $name . ' (' . $stmt->rowCount() . ' record).';
}
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['form'] ?? '') === 'style') { // odoslaný formulár na style
$name = $_POST['name'];
if ($name === '') {
$message = 'Vyplň názov style.';
} else {
$stmt = $pdo->prepare('SELECT id FROM styles WHERE name = ?');
$stmt->execute([$name]);
if ($stmt->fetch()) {
$message = 'Style ' . $name . ' už existuje.';
} else {
$stmt = $pdo->prepare('INSERT INTO styles (name) VALUES (?)'); // jeden otáznik
$stmt->execute([$name]);
$message = 'Pridaný style ' . $name . '.';
}
}
}
?>
<?php if ($message !== ''): ?>
<div class="alert alert-info"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>
<h2>Pridať do lookup tables</h2>
<div class="row g-4 mb-4">
<div class="col-md-6">
<form method="post" class="border rounded p-3">
<input type="hidden" name="form" value="grade"> <!-- ktorý z dvoch formulárov bol odoslaný -->
<h3 class="h5">Nový grade</h3>
<div class="mb-2">
<label class="form-label" for="grade-name">Grade</label>
<input class="form-control" id="grade-name" name="name" required>
</div>
<div class="mb-2">
<label class="form-label" for="grade-value">Hodnota na porovnávanie</label>
<input class="form-control" id="grade-value" name="value" type="number" step="0.1" required>
</div>
<button class="btn btn-primary">Pridať grade</button>
</form>
</div>
<div class="col-md-6">
<form method="post" class="border rounded p-3">
<input type="hidden" name="form" value="style">
<h3 class="h5">Nový style</h3>
<div class="mb-2">
<label class="form-label" for="style-name">Style</label>
<input class="form-control" id="style-name" name="name" required>
</div>
<button class="btn btn-primary">Pridať style</button>
</form>
</div>
</div>
<h2>Obsah tables</h2>
<p>Každá table tak, ako je v databáze: s id, foreign keys a dvojicami v pivot table. Nad tabuľkou je SQL, ktoré ju vypísalo. Record v lookup table má odkaz Upraviť a button Zmazať. Novú cestu pridáš v <a href="add-route.php">add-route.php</a>.</p>
<?php $editable = ['grades' => 'grade', 'styles' => 'style']; ?> <!-- lookup tables a slovo do názvu file: edit-grade.php, delete-grade.php -->
<?php foreach (['grades', 'styles', 'routes', 'route_styles'] as $table): ?> <!-- názvy tables sú v skripte, nie od používateľa -->
<?php
$sql = 'SELECT * FROM ' . $table; // preto stačí query
$rows = $pdo->query($sql)->fetchAll();
?>
<h3 class="h5 mt-4"><?= $table ?></h3>
<pre class="small"><?= $sql ?></pre>
<?php if ($rows): ?> <!-- prázdny array = table bez records -->
<table class="table table-sm table-striped">
<thead>
<tr>
<?php foreach (array_keys($rows[0]) as $column): ?> <!-- názvy columns = keys prvého record -->
<th><?= $column ?></th>
<?php endforeach; ?>
<?php if (isset($editable[$table])): ?> <!-- len lookup tables majú column s akciami -->
<th>akcia</th>
<?php endif; ?>
</tr>
</thead>
<tbody>
<?php foreach ($rows as $row): ?> <!-- každý record -->
<tr>
<?php foreach ($row as $value): ?> <!-- každá column v record -->
<td><?= htmlspecialchars($value ?? '') ?></td> <!-- ?? '': column bez hodnoty je NULL, htmlspecialchars chce text -->
<?php endforeach; ?>
<?php if (isset($editable[$table])): ?>
<td>
<a class="btn btn-outline-primary btn-sm" href="edit-<?= $editable[$table] ?>.php?id=<?= $row['id'] ?>">Upraviť</a> <!-- id v URL -->
<form method="post" action="delete-<?= $editable[$table] ?>.php"> <!-- mazanie cez POST -->
<input type="hidden" name="id" value="<?= $row['id'] ?>"> <!-- id v hidden input -->
<button class="btn btn-outline-danger btn-sm">Zmazať</button>
</form>
</td>
<?php endif; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php else: ?>
<p class="text-muted">Table je prázdna.</p>
<?php endif; ?>
<?php endforeach; ?>
Databáza
(formuláre na nový record a ostatné tables sú na stránke tiež, v náhľade sú len lookup tables)
grades
SELECT * FROM grades
| id | name | value | akcia |
|---|---|---|---|
| 1 | 5a | 5.0 | Upraviť Zmazať |
| 2 | 6a | 6.0 | Upraviť Zmazať |
| 3 | 6b | 6.3 | Upraviť Zmazať |
styles
SELECT * FROM styles
| id | name | akcia |
|---|---|---|
| 3 | boulder | Upraviť Zmazať |
| 2 | lead | Upraviť Zmazať |
| 1 | toprope | Upraviť Zmazať |
What it looks like in the browser: the opened address is data.php. In the tables grades and styles every record has the link Upraviť and the button Zmazať. The link Upraviť next to grade 6b has the address edit-grade.php?id=3. The button Zmazať next to grade 6b sends a POST request to delete-grade.php with id 3. The tables routes and route_styles have no column akcia.
What each line does:
$editable = ['grades' => 'grade', 'styles' => 'style']: the key is the name of a lookup table, the value is the word used in the file name,isset($editable[$table]):truewhen the table being listed is in the array$editable,href="edit-<?= $editable[$table] ?>.php?id=<?= $row['id'] ?>": for the tablegradesand the record withid3 it producesedit-grade.php?id=3.
In your own application. In $editable list your lookup tables and the word used in the file name, e.g. ['genres' => 'genre', 'tags' => 'tag'].
Example 4: edit-grade.php (lookup table), UPDATE
<?php
// ROLA: lookup table grades, formulár na úpravu jedného record (file stránky)
// CRUD: Update
// OTVÁRA SA: z data.php, odkaz Upraviť v table grades: edit-grade.php?id=3
// ROBÍ: pripojí databázu, nastaví titulok a content file content/edit-grade.php
// VO SVOJEJ APLIKÁCII: edit- a názov lookup table v jednotnom čísle, napr. edit-genre.php
require 'db.php'; // pripojenie: content file bude mať $pdo
$title = 'Upraviť grade'; // titulok: vypíše ho template.php v <title> a v <h1>
$active = 'data'; // ktorá položka menu je zvýraznená
$content = 'content/edit-grade.php'; // content file tejto stránky
include 'template.php'; // template.php vypíše HTML a vloží content file
<?php
// ROLA: lookup table grades, formulár na úpravu jedného record (content file)
// CRUD: Update
// OTVÁRA SA: vkladá ho template.php, keď sa otvorí edit-grade.php?id=3
// ROBÍ: po odoslaní formulára vykoná UPDATE a vypíše správu; potom načíta record a vypíše formulár s jeho hodnotami
// VO SVOJEJ APLIKÁCII: zmeň názov table, columns a inputs podľa svojej lookup table
$id = $_GET['id'] ?? ''; // id z URL: edit-grade.php?id=3
$message = ''; // správa pre používateľa
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // formulár bol odoslaný
$name = $_POST['name']; // najprv všetko z $_POST do premenných
$value = $_POST['value'];
if ($name === '' || $value === '') {
$message = 'Vyplň grade aj hodnotu.';
} else {
$stmt = $pdo->prepare('SELECT id FROM grades WHERE name = ? AND id <> ?'); // má ten istý name iný record?
$stmt->execute([$name, $id]);
if ($stmt->fetch()) { // fetch vráti record alebo false
$message = 'Grade ' . $name . ' už existuje.';
} else {
$stmt = $pdo->prepare('UPDATE grades SET name = ?, value = ? WHERE id = ?');
$stmt->execute([$name, $value, $id]); // id na konci: posledný ? patrí k WHERE
$message = 'Záznam bol upravený.';
}
}
}
$stmt = $pdo->prepare('SELECT * FROM grades WHERE id = ?'); // record na úpravu, po UPDATE už s novými hodnotami
$stmt->execute([$id]);
$grade = $stmt->fetch();
if (!$grade) { // id v URL chýba alebo taký record nie je
echo '<p>Grade sa nenašiel.</p>';
return; // ďalej sa nič nevypíše
}
?>
<?php if ($message !== ''): ?>
<div class="alert alert-info"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>
<form method="post" class="row g-3"> <!-- bez action: request ide na tú istú adresu aj s ?id=3 -->
<div class="col-md-6">
<label class="form-label" for="name">Grade</label>
<input class="form-control" id="name" name="name" value="<?= htmlspecialchars($grade['name']) ?>" required> <!-- value: hodnota z databázy -->
</div>
<div class="col-md-6">
<label class="form-label" for="value">Hodnota na porovnávanie</label>
<input class="form-control" id="value" name="value" type="number" step="0.1" value="<?= $grade['value'] ?>" required>
</div>
<div class="col-12">
<button class="btn btn-primary">Uložiť zmeny</button>
<a class="btn btn-outline-secondary" href="data.php">Späť</a>
</div>
</form>
Upraviť grade
What it looks like in the browser: after clicking Upraviť next to grade 6b in data.php the address edit-grade.php?id=3 opens. The inputs of the form hold the values from the database: 6b and 6.3.
Upraviť grade
After changing the values to 6b+ and 6.4 and clicking Uložiť zmeny the address stays edit-grade.php?id=3. Above the form is the message “Záznam bol upravený.” (The record was updated.) and the form shows the new values. UPDATE was executed: UPDATE grades SET name = '6b+', value = 6.4 WHERE id = 3. When 5a is typed into the input Grade, the message above the form is “Grade 5a už existuje.” and UPDATE is not executed. The address edit-grade.php?id=99 prints “Grade sa nenašiel.” (Grade not found.)
In your own application. A page file edit-LOOKUP.php and a content file content/edit-LOOKUP.php for every lookup table. Change the name of the table, the columns in SET, the inputs in the form and the texts of the messages. In the sample edit-style.php for the table styles is built the same way.
Example 5: delete-grade.php (lookup table), DELETE with a check
<?php
// ROLA: lookup table grades, zmazanie jedného record (file bez stránky, nemá content file)
// CRUD: Delete
// OTVÁRA SA: z data.php, button Zmazať v table grades (formulár POST s hidden input id)
// ROBÍ: zistí, či je grade použitý v routes; ak nie, vykoná DELETE; potom redirect na data.php so správou
// VO SVOJEJ APLIKÁCII: delete- a názov lookup table v jednotnom čísle, napr. delete-genre.php
require 'db.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { // file otvorený cez adresu (GET): nič sa nemaže
header('Location: data.php'); // header pošle prehliadaču adresu, na ktorú má prejsť
exit; // exit ukončí skript, ďalej sa nič nevykoná
}
$id = $_POST['id']; // id z hidden input vo formulári s buttonom Zmazať
$stmt = $pdo->prepare('SELECT COUNT(*) AS routes_count FROM routes WHERE grade_id = ?');
$stmt->execute([$id]);
$row = $stmt->fetch(); // jeden record s počtom
if ($row['routes_count'] > 0) { // record je použitý: DELETE by databáza odmietla (RESTRICT)
header('Location: data.php?msg=used');
exit;
}
$stmt = $pdo->prepare('DELETE FROM grades WHERE id = ?');
$stmt->execute([$id]); // vykoná sa DELETE
header('Location: data.php?msg=deleted'); // redirect: prehliadač otvorí data.php so správou
exit;
Databáza
grades
SELECT * FROM grades
| id | name | value | akcia |
|---|---|---|---|
| 1 | 5a | 5.0 | Upraviť Zmazať |
| 2 | 6a | 6.0 | Upraviť Zmazať |
| 3 | 6b | 6.3 | Upraviť Zmazať |
What it looks like in the browser: after clicking Zmazať next to grade 5a in data.php the address data.php?msg=used opens. Below the title is the message “Záznam sa nedá zmazať, je použitý.” and grade 5a is still in the table. SELECT returned routes_count 2, DELETE was not executed.
Databáza
styles
SELECT * FROM styles
| id | name | akcia |
|---|---|---|
| 2 | lead | Upraviť Zmazať |
| 1 | toprope | Upraviť Zmazať |
On the data from seed.sql every grade has at least one route. In the sample a successful DELETE is shown by the table styles: the style boulder is in no pair. After clicking Zmazať next to the style boulder in data.php, DELETE FROM styles WHERE id = 3 is executed in delete-style.php and the address data.php?msg=deleted opens. Below the title is the message “Záznam bol zmazaný.” (The record was deleted.) and the table styles keeps lead and toprope.
In your own application. A file delete-LOOKUP.php for every lookup table, without a content file. Change the name of the table in DELETE and the SELECT with the check: for a lookup table with a 1:N relation the records of the main entity are counted (WHERE grade_id = ?), for a lookup table with an M:N relation the pairs in the pivot table (WHERE style_id = ?).
Example 6: detail.php (main entity), the link Upraviť and the button Zmazať
content/detail.php from cv07 prints one route. In cv08 the SELECT has the column routes.id and below the output are the link Upraviť and the button Zmazať.
<?php
// ROLA: main entity, detail jedného record (file stránky)
// CRUD: Read
// OTVÁRA SA: z routes.php, odkaz detail: detail.php?id=2
// ROBÍ: pripojí databázu, nastaví titulok a content file content/detail.php
// VO SVOJEJ APLIKÁCII: názov detail.php zostáva, zmeň $title a $active
require 'db.php'; // pripojenie: content file bude mať $pdo
$title = 'Detail cesty'; // titulok: vypíše ho template.php v <title> a v <h1>
$active = 'routes'; // ktorá položka menu je zvýraznená
$content = 'content/detail.php'; // content file tejto stránky
include 'template.php'; // template.php vypíše HTML a vloží content file
<?php
// ROLA: main entity, detail jedného record (content file)
// CRUD: Read
// OTVÁRA SA: vkladá ho template.php, keď sa otvorí detail.php?id=2
// ROBÍ: vypíše cestu s grade a styles; má odkaz Upraviť (edit-route.php?id=2) a button Zmazať (delete-route.php)
// VO SVOJEJ APLIKÁCII: zmeň SQL a výpis podľa svojej main entity
$id = $_GET['id'] ?? ''; // id z URL: detail.php?id=2
// ZLE: hodnota z URL vlepená priamo do SQL (nechané v komentári len ako ukážka, nikdy nepoužívať)
// $stmt = $pdo->query("SELECT routes.name, holds, grades.name AS grade, since, note FROM routes
// JOIN grades ON routes.grade_id = grades.id WHERE routes.id = $id");
// DOBRE: hodnota z URL cez prepare
$stmt = $pdo->prepare('SELECT routes.id, routes.name, holds, grades.name AS grade, since, note
FROM routes JOIN grades ON routes.grade_id = grades.id
WHERE routes.id = ?');
$stmt->execute([$id]);
$route = $stmt->fetch(); // jeden record alebo false
if (!$route) { // id neexistuje alebo nie je číslo
echo '<p>Cesta sa nenašla.</p>';
return; // ďalej sa nič nevypíše
}
$stmt = $pdo->prepare('SELECT styles.name FROM route_styles
JOIN styles ON styles.id = route_styles.style_id
WHERE route_styles.route_id = ?'); // styles tejto cesty cez pivot table
$stmt->execute([$id]);
$styles = $stmt->fetchAll();
?>
<h2><?= htmlspecialchars($route['name']) ?></h2>
<p>Grade <?= htmlspecialchars($route['grade']) ?>, chyty <?= htmlspecialchars($route['holds']) ?>, postavená <?= $route['since'] ?></p>
<p><?= htmlspecialchars($route['note'] ?? '') ?></p> <!-- note je nepovinná, môže byť NULL -->
<p>Styles:
<?php foreach ($styles as $style): ?>
<span class="badge text-bg-secondary"><?= htmlspecialchars($style['name']) ?></span>
<?php endforeach; ?>
</p>
<a class="btn btn-outline-primary btn-sm" href="edit-route.php?id=<?= $route['id'] ?>">Upraviť</a> <!-- id v URL -->
<form method="post" action="delete-route.php" class="d-inline"> <!-- mazanie cez POST -->
<input type="hidden" name="id" value="<?= $route['id'] ?>"> <!-- id v hidden input -->
<button class="btn btn-outline-danger btn-sm">Zmazať</button>
</form>
<a class="btn btn-outline-secondary btn-sm" href="routes.php">Späť</a>
Detail cesty
Modrý previs
Grade 6a, chyty modré, postavená 2026-09-21
Previs s dobrými chytmi.
Styles: toprope lead
Upraviť Zmazať Späť
What it looks like in the browser: after clicking detail on the route Modrý previs in routes.php the address detail.php?id=2 opens. The link Upraviť has the address edit-route.php?id=2. The button Zmazať sends a POST request to delete-route.php with id 2.
In your own application. Add a link to edit-ENTITY.php?id=... and a form with action="delete-ENTITY.php" to content/detail.php. The SELECT must return the id of the main entity.
Example 7: edit-route.php (main entity), UPDATE with the pivot table
<?php
// ROLA: main entity, formulár na úpravu jedného record (file stránky)
// CRUD: Update
// OTVÁRA SA: z detail.php, odkaz Upraviť: edit-route.php?id=2
// ROBÍ: pripojí databázu, nastaví titulok a content file content/edit-route.php
// VO SVOJEJ APLIKÁCII: edit- a názov main entity v jednotnom čísle, napr. edit-book.php
require 'db.php'; // pripojenie: content file bude mať $pdo
$title = 'Upraviť cestu'; // titulok: vypíše ho template.php v <title> a v <h1>
$active = 'routes'; // ktorá položka menu je zvýraznená
$content = 'content/edit-route.php'; // content file tejto stránky
include 'template.php'; // template.php vypíše HTML a vloží content file
<?php
// ROLA: main entity, formulár na úpravu jedného record (content file)
// CRUD: Update
// OTVÁRA SA: vkladá ho template.php, keď sa otvorí edit-route.php?id=2
// ROBÍ: po odoslaní formulára vykoná UPDATE v routes a nanovo zapíše dvojice do pivot table; potom vypíše formulár s hodnotami z databázy
// VO SVOJEJ APLIKÁCII: zmeň názvy tables, columns a inputs; formulár je ten istý ako v add-ENTITY.php, len s vyplnenými hodnotami
$id = $_GET['id'] ?? ''; // id z URL: edit-route.php?id=2
$message = '';
$stmt = $pdo->prepare('SELECT id FROM routes WHERE id = ?'); // existuje cesta s týmto id?
$stmt->execute([$id]);
if (!$stmt->fetch()) { // bez cesty sa nedá upravovať ani zapisovať dvojice
echo '<p>Cesta sa nenašla.</p>';
return;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // formulár bol odoslaný
$name = $_POST['name'];
$holds = $_POST['holds'];
$gradeId = $_POST['grade_id']; // id zo selectu
$since = $_POST['since'];
$note = $_POST['note'];
$styleIds = $_POST['style'] ?? []; // array zaškrtnutých id; keď nič, prázdny array
if ($name === '' || $holds === '' || $gradeId === '' || $since === '') {
$message = 'Vyplň názov, chyty, grade a dátum.';
} else {
$stmt = $pdo->prepare('UPDATE routes SET name = ?, holds = ?, grade_id = ?, since = ?, note = ? WHERE id = ?');
$stmt->execute([$name, $holds, $gradeId, $since, $note, $id]); // UPDATE main entity; id na konci patrí k WHERE
$stmt = $pdo->prepare('DELETE FROM route_styles WHERE route_id = ?');
$stmt->execute([$id]); // pivot table: zmažú sa všetky dvojice tejto cesty
$stmt = $pdo->prepare('INSERT INTO route_styles (route_id, style_id) VALUES (?, ?)'); // prepare raz
foreach ($styleIds as $styleId) { // a zapíšu sa nanovo podľa zaškrtnutých checkboxov
$stmt->execute([$id, $styleId]);
}
$message = 'Záznam bol upravený.';
}
}
$stmt = $pdo->prepare('SELECT * FROM routes WHERE id = ?'); // cesta na úpravu, po UPDATE už s novými hodnotami
$stmt->execute([$id]);
$route = $stmt->fetch();
$stmt = $pdo->prepare('SELECT style_id FROM route_styles WHERE route_id = ?'); // dvojice tejto cesty
$stmt->execute([$id]);
$routeStyleIds = array_column($stmt->fetchAll(), 'style_id'); // array_column vyberie jednu column: [1, 2]
$grades = $pdo->query('SELECT id, name FROM grades ORDER BY value')->fetchAll(); // pre select
$styles = $pdo->query('SELECT id, name FROM styles ORDER BY name')->fetchAll(); // pre checkboxy
?>
<?php if ($message !== ''): ?>
<div class="alert alert-info"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>
<form method="post" class="row g-3"> <!-- bez action: request ide na tú istú adresu aj s ?id=2 -->
<div class="col-md-6">
<label class="form-label" for="name">Názov cesty</label>
<input class="form-control" id="name" name="name" value="<?= htmlspecialchars($route['name']) ?>" required>
</div>
<div class="col-md-6">
<label class="form-label" for="holds">Farba chytov</label>
<input class="form-control" id="holds" name="holds" value="<?= htmlspecialchars($route['holds']) ?>" required>
</div>
<div class="col-md-6">
<label class="form-label" for="grade_id">Grade</label>
<select class="form-select" id="grade_id" name="grade_id" required>
<?php foreach ($grades as $grade): ?>
<option value="<?= $grade['id'] ?>" <?= $grade['id'] == $route['grade_id'] ? 'selected' : '' ?>><?= htmlspecialchars($grade['name']) ?></option> <!-- selected: grade tejto cesty -->
<?php endforeach; ?>
</select>
</div>
<div class="col-md-6">
<label class="form-label" for="since">Postavená od</label>
<input class="form-control" id="since" name="since" type="date" value="<?= $route['since'] ?>" required>
</div>
<div class="col-12">
<label class="form-label" for="note">Poznámka</label>
<textarea class="form-control" id="note" name="note" rows="2"><?= htmlspecialchars($route['note'] ?? '') ?></textarea> <!-- textarea nemá value, text je medzi tagmi -->
</div>
<div class="col-12">
<span class="form-label d-block">Styles</span>
<?php foreach ($styles as $style): ?>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="style-<?= $style['id'] ?>" name="style[]" value="<?= $style['id'] ?>" <?= in_array($style['id'], $routeStyleIds) ? 'checked' : '' ?>> <!-- in_array: je id medzi dvojicami cesty? -->
<label class="form-check-label" for="style-<?= $style['id'] ?>"><?= htmlspecialchars($style['name']) ?></label>
</div>
<?php endforeach; ?>
</div>
<div class="col-12">
<button class="btn btn-primary">Uložiť zmeny</button>
<a class="btn btn-outline-secondary" href="detail.php?id=<?= $route['id'] ?>">Späť</a>
</div>
</form>
Upraviť cestu
What it looks like in the browser: after clicking Upraviť in detail.php?id=2 the address edit-route.php?id=2 opens. The form is the same as in add-route.php, with the values of the route Modrý previs. Grade 6a is selected in the select. Lead and toprope are checked because $routeStyleIds is [1, 2].
Upraviť cestu
After choosing grade 6b, unchecking lead and clicking Uložiť zmeny the address stays edit-route.php?id=2. Above the form is the message “Záznam bol upravený.” UPDATE in routes was executed (grade_id is 3), DELETE of the pairs (2, 1) and (2, 2) in route_styles and INSERT of the pair (2, 1). In data.php the table route_styles has the pairs (1, 1) and (2, 1).
In your own application. A page file edit-ENTITY.php and a content file content/edit-ENTITY.php. Copy the form from content/add-ENTITY.php and add the values from the database to value, selected, checked and between the textarea tags. Change the names of tables and columns in UPDATE, DELETE, INSERT and SELECT.
Example 8: delete-route.php (main entity), DELETE
<?php
// ROLA: main entity, zmazanie jedného record (file bez stránky, nemá content file)
// CRUD: Delete
// OTVÁRA SA: z detail.php, button Zmazať (formulár POST s hidden input id)
// ROBÍ: vykoná DELETE v routes; potom redirect na routes.php so správou
// VO SVOJEJ APLIKÁCII: delete- a názov main entity v jednotnom čísle, napr. delete-book.php
require 'db.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { // file otvorený cez adresu (GET): nič sa nemaže
header('Location: routes.php'); // header pošle prehliadaču adresu, na ktorú má prejsť
exit; // exit ukončí skript, ďalej sa nič nevykoná
}
$id = $_POST['id']; // id z hidden input vo formulári s buttonom Zmazať
// dvojice v pivot table route_styles zmaže databáza (ON DELETE CASCADE)
$stmt = $pdo->prepare('DELETE FROM routes WHERE id = ?');
$stmt->execute([$id]); // vykoná sa DELETE
header('Location: routes.php?msg=deleted'); // redirect: prehliadač otvorí routes.php so správou
exit;
Cesty
Ciest: 3
Zelená platňa 5a
Chyty: zelené, postavená 2026-10-19
detailČervená platňa 6b
Chyty: červené, postavená 2026-10-05
detailŽltá hrana 5a
Chyty: žlté, postavená 2026-09-14
detailWhat it looks like in the browser: after clicking Zmazať in detail.php?id=2, DELETE FROM routes WHERE id = 2 is executed and the address routes.php?msg=deleted opens. Below the title Cesty is the message “Záznam bol zmazaný.” and the list shows Zelená platňa, Červená platňa and Žltá hrana. The pairs (2, 1) and (2, 2) were deleted from route_styles by the database (ON DELETE CASCADE); the pivot table keeps the pair (1, 1).
In your own application. A file delete-ENTITY.php without a content file. Change the name of the table and the address in header() to ENTITY.php. When the pivot table in schema.sql has no ON DELETE CASCADE, DELETE FROM pivot_table WHERE ... = ? belongs before the DELETE from the main entity.
Example 9: prompts
Prompt U helps with unify.txt. Attach unify.txt, sql/schema.sql and the table of roles from the part What the application consists of.
I attach unify.txt from the course Internet Technologies, sql/schema.sql and the table of roles with the file naming rule. In unify.txt check the lines entity and lookup against schema.sql. Replace every question mark with a new file name according to the table of roles or with the word zmazat. Do not change lines without a question mark. Return the whole unify.txt and below it, for every changed line, one sentence saying which role the file has and why.
Prompt A, UPDATE and DELETE for a lookup table. Attach sql/schema.sql, web/template.php, web/content/data.php and the files created by unify.py: web/edit-LOOKUP.php, web/content/edit-LOOKUP.php, web/delete-LOOKUP.php.
A PHP application: a page consists of the page file web/X.php ($title, $active, $content, include 'template.php') and the content file web/content/X.php. $pdo is ready in db.php. For the lookup table LOOKUP from schema.sql complete the attached files; keep the comment with the role at the beginning of every file. 1. content/data.php: in the table of the lookup table add a column akcia with the link Upraviť (edit-LOOKUP.php?id=...) and a form method POST action delete-LOOKUP.php with a hidden input id and the button Zmazať. 2. content/edit-LOOKUP.php: id from $_GET; after POST values from $_POST into variables, check of required values, SELECT ... WHERE name = ? AND id <> ? with fetch as a duplicate check, UPDATE ... WHERE id = ? with prepare and execute, a message into $message; then SELECT the record by id, when it does not exist a message and return; the message in an alert and a Bootstrap form method POST without action with the values from the database in value. 3. delete-LOOKUP.php without a content file and without the template: require 'db.php'; when the request is not POST, header('Location: data.php') and exit; id from $_POST; SELECT COUNT(*) on the table that points to LOOKUP with a foreign key; when the count is greater than 0, redirect to data.php?msg=used; otherwise DELETE with prepare and execute and redirect to data.php?msg=deleted; exit after every header. 4. template.php: at the beginning the array $messages with the keys deleted and used, below <h1> the message for $_GET['msg'] in an alert. No functions or classes, a comment on every line in Slovak. Leave the texts of the messages as // DOPLŇ.
Prompt B, UPDATE and DELETE for the main entity. Attach sql/schema.sql, web/content/add-ENTITY.php, web/content/detail.php and the files created by unify.py: web/edit-ENTITY.php, web/content/edit-ENTITY.php, web/delete-ENTITY.php.
For the same application complete the attached files for the main entity ENTITY; keep the comment with the role at the beginning of every file. 1. content/detail.php: the SELECT should also return id; below the output the link Upraviť (edit-ENTITY.php?id=...) and a form method POST action delete-ENTITY.php with a hidden input id and the button Zmazať. 2. content/edit-ENTITY.php: keep the form from the attached content/add-ENTITY.php, change only what I write. id from $_GET; first SELECT whether the record exists, otherwise a message and return. After POST: values from $_POST into variables, check of required values, UPDATE ... WHERE id = ?, then DELETE of the pairs of this record in the pivot table and INSERT of the checked ones in a foreach with one prepared statement, a message into $message. Then SELECT the record and SELECT its pairs, array_column to get an array of ids. In the form the values from the database: value for input, text between the textarea tags, selected for option, checked with in_array for checkbox. 3. delete-ENTITY.php without a content file and without the template: require 'db.php'; when the request is not POST, redirect to ENTITY.php; id from $_POST; DELETE with prepare and execute; header('Location: ENTITY.php?msg=deleted') and exit. No functions or classes, a comment on every line in Slovak. Leave the validation rules as // DOPLŇ.
Why the prompts are written this way:
- attached files instead of a description: the AI sees the exact names of tables, columns and files and completes them,
- “keep the comment with the role”: the map of the application in
README.mdand the comments in the files stay the same, - “keep the form, change only what I write” stops the AI from rewriting the form from cv07,
- “without a content file and without the template” for delete: the AI puts no HTML into the file and
header()works, - “exit after every header”: without
exitDELETE would be executed even after the check, // DOPLŇleaves the texts of the messages and the validation rules to the author of the application,- prompt U changes only the lines with a question mark: renaming is done by
unify.py, the AI only proposes names.
Úlohy na cvičenieLab tasks
Prijať zadanie cv08 v Classroom 50 (platí pre skupiny B. Stehlíkovej; ostatné skupiny dostanú link od svojho cvičiaceho).
Výsledkom cv08 je hotová aplikácia: files majú názvy podľa tabuľky rolí a lookup tables aj main entity majú každú operáciu CRUD. ENTITY je názov table svojej main entity, LOOKUP názov svojej lookup table.
9.1 Kubeflow: skontroluj rozšírenia (SFTP, Five Server, Intelephense). Ak chýbajú, spusti v termináli príkaz na obnovu z návodu 04 Odovzdávanie.
9.2 git clone repository cv08. V repository je README.md a unify.py. Prekopíruj aplikáciu z cv07:
rsync -a --exclude .git --exclude README.md cv07/ cv08/
V Adminer spusti schema.sql a potom seed.sql, aby aplikácia začínala z čistých dát. Commit.
9.3 Unifikácia (ukážka 1). V priečinku cv08 spusti python3 unify.py --init. Otvor unify.txt, skontroluj riadky entity a lookup a nahraď každý otáznik názvom podľa tabuľky rolí alebo slovom zmazat (pomôže prompt U). Spusti python3 unify.py, prečítaj plán a potom python3 unify.py --run.
9.4 Dokonči, čo script vypísal pod „Treba dokončiť”. Menu v template.php má odkazy na index.php, ENTITY.php, add-ENTITY.php, data.php, stats.php a contact.php. Spusti python3 unify.py --check. V prehliadači otvor každú položku menu. Commit.
9.5 Lookup table, UPDATE (ukážky 3 a 4, prompt A). V content/data.php má každý record lookup table odkaz Upraviť. edit-LOOKUP.php s content/edit-LOOKUP.php: formulár s hodnotami z databázy, UPDATE cez prepare a execute, kontrola duplicity s AND id <> ?, správa nad formulárom. Over: uloženie bez zmeny, uloženie so zmenou, name, ktorý už má iný record.
9.6 Lookup table, DELETE (ukážky 2 a 5, prompt A). V content/data.php má každý record lookup table button Zmazať vo formulári method="post". delete-LOOKUP.php: kontrola použitia cez SELECT COUNT(*), DELETE, redirect. V template.php array $messages a výpis správy pod <h1>. Over: zmazanie použitého record, zmazanie record, ktorý použitý nie je. Commit.
9.7 To isté ako 9.5 a 9.6 pre každú ďalšiu lookup table (vo vzore edit-style.php a delete-style.php). Pri lookup table s reláciou M:N kontrola počíta dvojice v pivot table.
9.8 Main entity, odkaz Upraviť a button Zmazať v content/detail.php (ukážka 6, prompt B).
9.9 Main entity, UPDATE (ukážka 7, prompt B). edit-ENTITY.php s content/edit-ENTITY.php: formulár z content/add-ENTITY.php s hodnotami z databázy, UPDATE, DELETE dvojíc v pivot table, INSERT zaškrtnutých, správa nad formulárom. Over v data.php, že dvojice v pivot table sedia so zaškrtnutými checkboxmi. Commit.
9.10 Main entity, DELETE (ukážka 8, prompt B). delete-ENTITY.php: DELETE a redirect na ENTITY.php?msg=deleted. Over v data.php, že so zmazaným record zmizli aj jeho dvojice v pivot table. Do komentára v delete-ENTITY.php napíš, ktorý riadok v schema.sql to zabezpečil.
9.11 Spusti python3 unify.py --check a over, že mapa aplikácie v README.md sedí s files vo web/. Commit a push, aspoň 4 commity v rôznych krokoch (napr. po 9.2, 9.4, 9.6, 9.9).
9.12 Upload Folder: cv08 do ti/cv08/ a obsah web/ do ti/projekt/. Over vo svojom webovom priestore na sigma.tuke.sk: každá položka menu funguje, úprava a zmazanie fungujú pre lookup tables aj main entity, po každej operácii je správa.
Hodnotenie: 1 bod. Aplikácia s názvami files podľa tabuľky rolí, s úpravou a zmazaním record v lookup tables aj v main entity s pivot table a so správou po každej operácii funguje vo svojom webovom priestore na sigma.tuke.sk, kód je v repository. Po push sa spustia testy (25 kontrol); zelený výsledok znamená, že files a požadované časti kódu sú na mieste, body udeľuje učiteľka.
Accept assignment cv08 in Classroom 50 (applies to B. Stehlíková’s groups; other groups get the link from their own teacher).
The result of cv08 is a complete application: the files are named according to the table of roles and the lookup tables and the main entity have every CRUD operation. ENTITY is the name of the table of your main entity, LOOKUP the name of your lookup table.
9.1 Kubeflow: check the extensions (SFTP, Five Server, Intelephense). If they are missing, run the restore command from the guide 04 Submitting in the terminal.
9.2 git clone the repository cv08. It contains README.md and unify.py. Copy the application from cv07:
rsync -a --exclude .git --exclude README.md cv07/ cv08/
In Adminer run schema.sql and then seed.sql so that the application starts from clean data. Commit.
9.3 Unification (example 1). In the folder cv08 run python3 unify.py --init. Open unify.txt, check the lines entity and lookup and replace every question mark with a name from the table of roles or with the word zmazat (prompt U helps). Run python3 unify.py, read the plan and then run python3 unify.py --run.
9.4 Finish what the script printed under „Treba dokončiť” (to be finished). The menu in template.php has links to index.php, ENTITY.php, add-ENTITY.php, data.php, stats.php and contact.php. Run python3 unify.py --check. Open every menu item in the browser. Commit.
9.5 Lookup table, UPDATE (examples 3 and 4, prompt A). In content/data.php every record of a lookup table has the link Upraviť. edit-LOOKUP.php with content/edit-LOOKUP.php: a form with the values from the database, UPDATE with prepare and execute, a duplicate check with AND id <> ?, a message above the form. Verify: saving without a change, saving with a change, a name that another record already has.
9.6 Lookup table, DELETE (examples 2 and 5, prompt A). In content/data.php every record of a lookup table has the button Zmazať in a form with method="post". delete-LOOKUP.php: a check of use with SELECT COUNT(*), DELETE, redirect. In template.php the array $messages and the message printed below <h1>. Verify: deleting a used record, deleting a record that is not used. Commit.
9.7 The same as 9.5 and 9.6 for every other lookup table (in the sample edit-style.php and delete-style.php). For a lookup table with an M:N relation the check counts the pairs in the pivot table.
9.8 Main entity, the link Upraviť and the button Zmazať in content/detail.php (example 6, prompt B).
9.9 Main entity, UPDATE (example 7, prompt B). edit-ENTITY.php with content/edit-ENTITY.php: the form from content/add-ENTITY.php with the values from the database, UPDATE, DELETE of the pairs in the pivot table, INSERT of the checked ones, a message above the form. Verify in data.php that the pairs in the pivot table match the checked checkboxes. Commit.
9.10 Main entity, DELETE (example 8, prompt B). delete-ENTITY.php: DELETE and a redirect to ENTITY.php?msg=deleted. Verify in data.php that the pairs of the deleted record disappeared from the pivot table. In a comment in delete-ENTITY.php write which line of schema.sql ensured that.
9.11 Run python3 unify.py --check and verify that the map of the application in README.md matches the files in web/. Commit and push, at least 4 commits at different steps (e.g. after 9.2, 9.4, 9.6, 9.9).
9.12 Upload Folder: cv08 to ti/cv08/ and the content of web/ to ti/projekt/. Verify in your web space on sigma.tuke.sk: every menu item works, editing and deleting work for the lookup tables and the main entity, there is a message after every operation.
Grading: 1 point. The application with file names according to the table of roles, with editing and deleting of a record in the lookup tables and in the main entity with the pivot table and with a message after every operation works in your web space on sigma.tuke.sk, and the code is in the repository. Tests run after the push (25 checks); a green result means the files and the required parts of the code are in place, points are awarded by the teacher.
Obhajoba a live codingDefence and live coding
Pred obhajobou kola 2 si odovzdaný stav skopíruješ: rsync -a --exclude .git cv08/ obhajoba2/ a Upload Folder. Live coding sa robí v obhajoba2, odovzdaný stav sa nedotkne. Pri obhajobe budú použité iba zverejnené otázky a úlohy. Obhajuje sa aplikácia v stave po cv08, teda aj to, čo vzniklo v cv07.
Vysvetli (code walkthrough)
- Čo znamená CRUD a ktorý SQL príkaz patrí ku ktorému písmenu.
- Na mape aplikácie v
README.mdukáž pre lookup table a pre main entity file ku každej operácii CRUD. - Akú rolu má file stránky a akú content file; ukáž dvojicu s rovnakým názvom.
- Prečo
delete-LOOKUP.phpnemá content file. - Prejdi kroky od kliknutia na Upraviť po zobrazenie formulára: ktorý file sa spustí, čo pripojí, kde sa začne vypisovať HTML.
- Odkiaľ je v
content/edit-LOOKUP.phpida odkiaľ nové hodnoty. - Čo by spravil UPDATE bez
WHERE. - Prečo je
$idvexecute([...])posledné. - Prečo je SELECT record v content file na úpravu až za UPDATE.
- Čo robí
AND id <> ?v kontrole duplicity a čo by sa stalo bez neho. - Kam sa vo formulári na úpravu píše hodnota z databázy pri
input,textarea,selectacheckbox. - Prečo formulár na úpravu nemá
actiona na akú adresu ide request po odoslaní. - Prečo je button Zmazať formulár
method="post"a nie odkaz. - Ako sa
iddostane z buttonu Zmazať dodelete-LOOKUP.php. - Čo spraví
delete-LOOKUP.php, keď ho niekto otvorí cez adresu v prehliadači. - Čo robí
header('Location: ...')a čoexit; čo by sa stalo bezexitpo kontrole použitia. - Prečo redirect nie je v content file; aká hláška by sa vypísala.
- Ako sa správa po zmazaní dostane na stránku: čo je v URL, čo v
$messages, kde sa vypíše. - Prečo je v URL key a nie text správy.
- Čo znamená
ON DELETE RESTRICTaON DELETE CASCADEvschema.sql; ukáž, kde sa každé prejaví v aplikácii. - Čo vráti
SELECT COUNT(*) ...pred DELETE z lookup table a čo by vrátila databáza bez tejto kontroly. - Ktoré SQL príkazy sa vykonajú po uložení formulára na úpravu main entity a v akom poradí.
- Čo vráti
array_columna čoin_array; ukáž, kde sú vcontent/edit-ENTITY.php. - Čo sa stane s dvojicami v pivot table po zmazaní record main entity a prečo.
Uprav (live coding)
- Zmeň text správy po zmazaní v
template.php. - Pridaj do
$messagesnový keyupdateds textom a ukáž ho cez adresu s?msg=updated. - V
content/edit-LOOKUP.phpzmeň text správy po úspešnom UPDATE tak, aby obsahoval novýname. - V
content/edit-ENTITY.phpurob jeden nepovinný input povinným a ukáž správu. - V
content/data.phpzmeň text odkazu Upraviť a Bootstrap class buttonu Zmazať. - V
content/edit-LOOKUP.phpzmeň adresu odkazu Späť. - V
delete-ENTITY.phpzmeň adresu redirect nadata.phpa ukáž, kde sa správa zobrazí. - V Adminer napíš SELECT, ktorý vráti records lookup table, ktoré sa dajú zmazať (LEFT JOIN + IS NULL).
- V
content/edit-ENTITY.phpzmeň poradie checkboxov cezORDER BYv SELECT. - Do
content/detail.phppridaj odkaz naadd-ENTITY.php.
Zdôvodni (design decisions)
- Prečo sa UPDATE vykonáva v content file a DELETE vo file bez stránky.
- Prečo je správa po redirect v
template.phpa nie vcontent/data.php. - Prečo sa pri úprave main entity dvojice v pivot table zmažú a zapíšu nanovo.
- Prečo aplikácia kontroluje použitie record pred DELETE, keď to isté stráži databáza.
- Prečo majú files názvy podľa roly a nie podľa titulku stránky.
- Prečo do repository nepatria files, ktoré aplikácia nepoužíva.
Definition of Done
- názvy files sú podľa tabuľky rolí,
python3 unify.py --checknevypíše nič na dokončenie, - každý file vo
web/aweb/content/má na začiatku komentár s rolou, README.mdobsahuje mapu aplikácie,- každá položka menu vedie na fungujúcu stránku,
- každá lookup table má v
data.phpodkaz Upraviť a button Zmazať, úprava aj zmazanie fungujú, - zmazanie použitého record lookup table skončí správou, nie chybou databázy,
- main entity má v
detail.phpodkaz Upraviť a button Zmazať, úprava mení aj dvojice v pivot table, - po každom INSERT, UPDATE a DELETE je na stránke správa,
- všetko vo webovom priestore na sigma.tuke.sk (
ti/cv08/ati/projekt/) a v repository s aspoň 4 commitmi.
Before the defence of round 2 you copy the submitted state: rsync -a --exclude .git cv08/ obhajoba2/ and Upload Folder. Live coding is done in obhajoba2, the submitted state is not touched. Only the published questions and tasks are used at the defence. The application is defended in its state after cv08, including what was created in cv07.
Explain (code walkthrough)
- What CRUD means and which SQL statement belongs to which letter.
- On the map of the application in
README.mdshow the file for every CRUD operation for a lookup table and for the main entity. - What role the page file has and what role the content file has; show a pair with the same name.
- Why
delete-LOOKUP.phphas no content file. - Go through the steps from clicking Upraviť to the form being displayed: which file runs, what it includes, where the HTML starts being printed.
- Where
idcomes from incontent/edit-LOOKUP.phpand where the new values come from. - What UPDATE without
WHEREwould do. - Why
$idis last inexecute([...]). - Why the SELECT of the record in a content file for editing comes after UPDATE.
- What
AND id <> ?does in the duplicate check and what would happen without it. - Where the value from the database goes in the edit form for
input,textarea,selectandcheckbox. - Why the edit form has no
actionand to which address the request goes after submitting. - Why the button Zmazať is a form with
method="post"and not a link. - How
idgets from the button Zmazať intodelete-LOOKUP.php. - What
delete-LOOKUP.phpdoes when somebody opens it through the address in the browser. - What
header('Location: ...')does and whatexitdoes; what would happen withoutexitafter the check of use. - Why the redirect is not in a content file; which message would be printed.
- How the message after deleting gets onto the page: what is in the URL, what is in
$messages, where it is printed. - Why the URL carries a key and not the text of the message.
- What
ON DELETE RESTRICTandON DELETE CASCADEmean inschema.sql; show where each one shows in the application. - What
SELECT COUNT(*) ...returns before DELETE from a lookup table and what the database would return without this check. - Which SQL statements are executed after saving the edit form of the main entity and in what order.
- What
array_columnreturns and whatin_arrayreturns; show where they are incontent/edit-ENTITY.php. - What happens to the pairs in the pivot table after a record of the main entity is deleted, and why.
Modify (live coding)
- Change the text of the message after deleting in
template.php. - Add a new key
updatedwith a text to$messagesand show it with an address containing?msg=updated. - In
content/edit-LOOKUP.phpchange the text of the message after a successful UPDATE so that it contains the newname. - In
content/edit-ENTITY.phpmake one optional input required and show the message. - In
content/data.phpchange the text of the link Upraviť and the Bootstrap class of the button Zmazať. - In
content/edit-LOOKUP.phpchange the address of the link Späť (Back). - In
delete-ENTITY.phpchange the address of the redirect todata.phpand show where the message appears. - In Adminer write a SELECT that returns the records of a lookup table that can be deleted (LEFT JOIN + IS NULL).
- In
content/edit-ENTITY.phpchange the order of the checkboxes withORDER BYin the SELECT. - Add a link to
add-ENTITY.phptocontent/detail.php.
Justify (design decisions)
- Why UPDATE is executed in a content file and DELETE in a file without a page.
- Why the message after a redirect is in
template.phpand not incontent/data.php. - Why the pairs in the pivot table are deleted and written again when the main entity is edited.
- Why the application checks whether a record is used before DELETE when the database guards the same thing.
- Why files are named by role and not by the title of the page.
- Why files the application does not use do not belong in the repository.
Definition of Done
- file names follow the table of roles,
python3 unify.py --checkprints nothing to finish, - every file in
web/andweb/content/starts with the comment with the role, README.mdcontains the map of the application,- every menu item leads to a working page,
- every lookup table has the link Upraviť and the button Zmazať in
data.php, editing and deleting work, - deleting a used record of a lookup table ends with a message, not with a database error,
- the main entity has the link Upraviť and the button Zmazať in
detail.php, editing also changes the pairs in the pivot table, - there is a message on the page after every INSERT, UPDATE and DELETE,
- everything is in your web space on sigma.tuke.sk (
ti/cv08/andti/projekt/) and in the repository with at least 4 commits.