V cvičení cv06 si vytvoril tables a napísal SQL queries v Adminer. Dnes to isté SQL pošle databáze PHP. Pôjdeme operáciu po operácii: pripojenie, zápis do lookup table, výpis lookup tables, zápis do main entity aj s pivot table, výpisy a filter. Na konci má aplikácia (vo vzore lezecká stena) routes.php (main entity, zoznam z databázy s filtrom), detail.php (main entity, detail), add-route.php (main entity, formulár na nový record), data.php (lookup tables, výpis každej table a formuláre na nový record) a stats.php (prehľad). Úprava a mazanie records pribudnú v cvičení cv08. Pojmy sú v tabuľke v týždni 1, roly files a pravidlo ich názvov v týždni 9.
Všetky ukážky používajú všeobecné pomenovanie main entity (hlavná entita), lookup table (číselník) a pivot table (prepojka) a v zátvorke konkrétny názov zo vzoru: routes, grades, styles, route_styles. Vo svojom projekte dosaď svoje tables.
In lab cv06 you created tables and wrote SQL queries in Adminer. Today PHP sends the same SQL to the database. We go operation by operation: connection, insert into a lookup table, listing lookup tables, insert into the main entity with its pivot table, listings and a filter. At the end the application (the climbing wall in the sample) has routes.php (main entity, a list from the database with a filter), detail.php (main entity, detail), add-route.php (main entity, form for a new record), data.php (lookup tables, a listing of every table and forms for a new record) and stats.php (overview). Editing and deleting records come in lab cv08. Terms are in the table in week 1, file roles and the naming rule in week 9.
All examples use the general names main entity, lookup table and pivot table, with the concrete name from the sample in brackets: routes, grades, styles, route_styles. In your own project substitute your tables.
TeóriaTheory
Čo sme robili doteraz a čo chceme teraz
V cvičení cv06 si písal SQL priamo. V Adminer si napísal query, spustil ju a výsledok si videl hneď: buď text, že príkaz sa vykonal alebo nevykonal, alebo tabuľku s nájdenými records.
Používateľ webu to takto robiť nemôže. Keby si chcel na stránke lezeckej steny pozrieť, aké cesty sú postavené, nedostaneš heslo do databázy a nebudeš písať vlastné SQL queries. Na webovej stránke ale môžeš: pozrieť si zoznam ciest, vyfiltrovať si len ľahké, pridať novú cestu cez formulár. Sú to tie isté operácie, SELECT a INSERT. Napíše ich a pošle za používateľa aplikácia.
Ako sa PHP dostane k databáze
PHP s databázou nekomunikuje priamo. Posiela jej SQL queries cez rozhranie s názvom PDO (PHP Data Objects). PDO je súčasť PHP. Robí to isté, čo si robil ty v Adminer: zoberie text SQL query, pošle ho databáze ako request a prevezme response, ktorú databáza vráti. Adminer je tiež iba PHP file, ktorý komunikuje cez server s databázou. Preto má v URL .php.
Viac: php.net: PDO
Pripojenie: file db.php
V Adminer si sa najprv prihlásil a až potom si mohol zadávať príkazy. PHP aplikácia sa musí prihlásiť ku databáze rovnako. Ak chceme používateľovi webu umožniť, aby cez INSERT vkladal a cez SELECT prezeral to, čo je v databáze, musíme mu dovoliť použiť prihlasovacie údaje aplikácie. Zároveň ich nesmie vidieť ani zneužiť. Preto sú údaje v PHP file na serveri, nie v HTML. Do prehliadača príde až hotový výsledok.
Pripojenie napíšeme raz, do web/db.php. Každá stránka, ktorá databázu potrebuje, ho pripojí cez require 'db.php'; na začiatku. Pripojenie potrebuje tieto údaje a nastavenia:
| Čo | Hodnota vo vzore | Vysvetlenie |
|---|---|---|
| DSN (Data Source Name) | mysql:host=localhost;dbname=teacher;charset=utf8mb4 |
aký databázový systém, kde beží, ktorá databáza, kódovanie (diakritika) |
| používateľ | teacher |
ako v Adminer |
| heslo | teacher_psw |
ako v Adminer |
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION |
pri chybe v SQL sa skript zastaví a vypíše hlášku. Bez toho chyba potichu zmizne a stránka je len prázdna. | |
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC |
každý record príde ako array, kde key je názov column: $row['name'] |
Svoje prihlasovacie údaje máš z cvičenia cv06. Údaje teacher sú fiktívne, len do ukážok.
Metódy: hotové príkazy, ktoré PDO pozná
PHP má pre komunikáciu cez PDO pripravené metódy (methods): hotové príkazy s názvom, ktoré PDO pozná a ktoré voláme zápisom $pdo->názov(...). Nemusíme vedieť, ako sú napísané vnútri. Stačí vedieť, čo ktorá robí a čo vráti. Na výpisy a zápisy ich budeme kombinovať: jedna pošle SQL query a ďalšia prevezme výsledok, ktorý vráti databáza.
Výsledok si vždy odložíme do premennej. Vo všetkých ukážkach sa volá $stmt (statement, príkaz). Je v nej SQL príkaz pripravený alebo už vykonaný a z nej potom vyberáme records.
| Metóda | Čo robí |
|---|---|
$stmt = $pdo->query('SQL'); |
pošle hotové SQL databáze, výsledok uloží do $stmt |
$stmt = $pdo->prepare('SQL s ?'); |
pripraví SQL s otáznikmi, hodnoty sa doplnia v ďalšom kroku |
$stmt->execute([hodnoty]); |
doplní hodnoty za otázniky a pošle SQL databáze |
$rows = $stmt->fetchAll(); |
výsledok query je tabuľka; každý riadok tabuľky je array |
$row = $stmt->fetch(); |
výsledok je jeden record, array |
$stmt->rowCount() |
číslo: koľko records príkaz zmenil |
$pdo->lastInsertId() |
číslo: id, ktoré databáza pridelila poslednému INSERT |
Prepare a execute: kde sú hodnoty
Hodnoty, ktoré idú do databázy, máme v PHP premenných. Najjednoduchší príklad, zápis jedného grade:
$name = $_POST['name']; // používateľ napísal 7a
$value = $_POST['value']; // používateľ napísal 7.0
$stmt = $pdo->prepare('INSERT INTO grades (name, value) VALUES (?, ?)'); // dva otázniky
$stmt->execute([$name, $value]); // prvý ? dostane $name, druhý ? dostane $value
V kroku prepare databáza dostane SQL s otáznikmi a pripraví si ho. V kroku execute dostane hodnoty, doplní ich na miesta otáznikov a príkaz vykoná. Otáznik sa volá placeholder (zástupný znak). Otáznikov je presne toľko, koľko prvkov má array v execute, a sú v rovnakom poradí.
Pravidlo: query alebo prepare
SQL query je buď celá napísaná v skripte a nikdy sa nemení, alebo do nej vstupuje hodnota od používateľa: z formulára alebo z URL. Podľa toho sa rozhoduje:
Ak SQL neobsahuje žiadnu hodnotu od používateľa, pošleme ju cez query. Ak do SQL vstupuje hodnota od používateľa, použijeme prepare s otáznikom na mieste hodnoty a execute s hodnotami.
| SQL | Odkiaľ je hodnota | Metóda |
|---|---|---|
SELECT id, name FROM grades ORDER BY value |
žiadna hodnota od používateľa | query |
SELECT COUNT(*) FROM routes |
žiadna hodnota od používateľa | query |
SELECT name FROM routes WHERE grade_id = ? |
grade_id zo selectu vo filtri, príde v URL | prepare + execute([$gradeId]) |
INSERT INTO grades (name, value) VALUES (?, ?) |
name a value prichádzajú z formulára, píše ich používateľ, predstavujú riziko injection |
prepare + execute([$name, $value]) |
INSERT INTO routes (name, holds, grade_id, since) VALUES (?, ?, ?, ?) |
každá hodnota je z formulára | prepare + execute([$name, $holds, $gradeId, $since]) |
SELECT * FROM routes WHERE id = ? |
id z URL: v routes.php klikneš na „detail”, URL je detail.php?id=2; hodnotu 2 vieš v adresnom riadku prepísať na čokoľvek |
prepare + execute([$id]) |
Hodnoty poslané cez execute databáza číta vždy len ako dáta, nikdy ako SQL. Keď používateľ napíše do input vo formulári ' OR 1=1, uloží sa presne tento text. Keď hodnotu vlepíme do SQL ako text, používateľ si môže v URL alebo v input dopísať vlastné SQL. To je SQL injection, ukážeme si ju v ukážke 7 na detaile cesty s prepísaným id. Pravidlo query/prepare je celá ochrana proti nej.
Čo vráti databáza
Databáza vráti vždy jedno z troch:
- Áno alebo nie. Pri INSERT databáza vráti, či sa príkaz vykonal.
executevrátitruealebofalse. V Adminer si to videl ako text „1 row affected”. - Číslo. Pri
SELECT COUNT(*)je výsledkom jedno číslo. Číslo vráti ajrowCount()(koľko records sa zmenilo) alastInsertId()(id nového record). Tu nemusíš nič vypisovať ani čítať z tabuľky, databáza vráti rovno číslo. - Records. Pri SELECT je výsledkom tabuľka. V Adminer si ju videl hneď na obrazovke. V PHP sa výsledok dostane do pamäte servera a na web sa bez ďalšieho kódu nedostane. Musíme ho odchytiť do premennej a pripraviť si, čo z neho vypíšeme. Na to sú
fetchAllafetch:
| Records vo výsledku | Metóda | Čo je v premennej | Keď databáza nič nenašla | Ako vypíšeme |
|---|---|---|---|---|
| viac | $rows = $stmt->fetchAll(); |
tabuľka: array, kde každý riadok je jeden record; record je array s názvami columns | prázdny array [], foreach nevypíše nič |
foreach ($rows as $row) { echo $row['name']; } |
| jeden | $row = $stmt->fetch(); |
jeden record, array | false |
if ($row) { echo $row['name']; } |
Kedy sa hodí číslo namiesto records:
$pdo->lastInsertId()po zápise do main entity. Databáza pridelila novému record id a to isté id potrebujeme zapísať do pivot table ku každému zaškrtnutému style.$stmt->rowCount()po INSERT ako kontrola, že sa zapísal jeden record. V cv08 pri UPDATE a DELETE vráti, koľko records sa zmenilo.
Výstup z databázy vypisujeme cez htmlspecialchars
Čo prečítame z databázy, vypíšeme rovnako ako hodnoty z formulára v týždni 6: cez htmlspecialchars(). V databáze je to, čo tam niekto zapísal, aj text so značkami < a >.
Formuláre a databáza
Formulár poznáš z týždňa 6: HTML form, PHP vezme hodnoty z $_POST do premenných a skontroluje ich. Dnes za kontrolu pridáme jeden krok: prepare + execute, ktorý hodnoty zapíše. Ukážky idú po files aplikácie lezecká stena, v tomto poradí:
data.php(lookup tables): výpis každej table tak, ako je, s id a foreign keys, a formuláre na pridanie record do lookup tables (grades, styles): jeden INSERT, kontrola duplicity cezfetch,add-route.php(main entity, nový record): formulár na main entity (routes) s pivot table (route_styles): select a checkboxy naplnené z lookup tables, jeden INSERT,lastInsertId, potom jeden INSERT za každý zaškrtnutý checkbox voforeach,routes.php(main entity, zoznam): zoznam z databázy cez JOIN a filter cez GET,detail.php(main entity, detail): cesta podľa id z URL, zlá a dobrá verzia (SQL injection),stats.php(prehľad): výpisy cez JOIN, pivot table s názvami, počet cezGROUP BY, jeden record cezfetch.
Najčastejšie chyby a čo znamenajú
Hlášky začínajú SQLSTATE[...]: to je kód chyby z databázy, ktorý PDO vypíše vďaka nastaveniu ERRMODE_EXCEPTION.
| Hláška | Príčina | Riešenie |
|---|---|---|
SQLSTATE[HY000] [1045] Access denied for user |
zlý používateľ alebo heslo v db.php |
skontroluj údaje z cvičenia cv06 |
SQLSTATE[HY000] [1049] Unknown database |
zlý názov databázy v DSN | názov databázy je rovnaký ako prihlasovacie meno |
SQLSTATE[42S02] Base table or view not found |
table neexistuje alebo preklep v názve | spusti schema.sql v Adminer, skontroluj názov |
SQLSTATE[42S22] Unknown column |
preklep v názve column | porovnaj so schema.sql |
SQLSTATE[23000] ... foreign key constraint fails |
zapisuješ id, ktoré v lookup table nie je | select vo formulári musí mať value = id z databázy |
SQLSTATE[23000] ... Duplicate entry |
hodnota s UNIQUE už existuje | druhýkrát ten istý grade sa nezapíše, to je správne správanie |
SQLSTATE[HY093] Invalid parameter number |
počet ? nesedí s počtom hodnôt v execute |
spočítaj otázniky a prvky array |
Call to a member function fetchAll() on bool |
query() dostal chybné SQL a vrátil false |
skús SQL v Adminer; skontroluj, že db.php má ERRMODE_EXCEPTION |
Trying to access array offset on false |
fetch() nič nenašiel a čítaš $row['name'] |
najprv if ($row) |
Array to string conversion |
vypisuješ array namiesto prvku | $row['name'], nie $row |
Undefined array key "style" |
žiadny checkbox nebol zaškrtnutý | $_POST['style'] ?? [] |
Undefined variable $pdo |
stránka nemá require 'db.php' |
pridaj require na začiatok stránky |
Deprecated: htmlspecialchars(): Passing null to parameter #1 |
column bez hodnoty (nepovinná note) je v databáze NULL, nie text |
htmlspecialchars($value ?? ''): ?? dá prázdny text, keď je hodnota NULL (týždeň 6) |
What we did so far and what we want now
In lab cv06 you wrote SQL directly. In Adminer you typed a query, ran it and saw the result at once: either a text saying the command was or was not executed, or a table with the records found.
A web user cannot work this way. If you wanted to see on the climbing wall site which routes are set, you would not get the database password and you would not write your own SQL queries. On a web page you can: see the list of routes, filter only the easy ones, add a new route through a form. These are the same operations, SELECT and INSERT. The application writes and sends them on the user’s behalf.
How PHP reaches the database
PHP does not communicate with the database directly. It sends SQL queries through an interface called PDO (PHP Data Objects). PDO is part of PHP. It does what you did in Adminer: takes the text of an SQL query, sends it to the database as a request and takes over the response the database returns. Adminer is also just a PHP file that communicates with the database through the server. That is why its URL ends in .php.
More: php.net: PDO
Connection: the file db.php
In Adminer you first logged in and only then could you run commands. A PHP application must log in to the database the same way. If we want to let the web user insert with INSERT and browse with SELECT what is in the database, we have to let them use the application’s login details. At the same time they must never see or misuse them. That is why the details are in a PHP file on the server, not in HTML. The browser receives only the finished result.
We write the connection once, into web/db.php. Every page that needs the database attaches it with require 'db.php'; at the top. The connection needs these details and settings:
| What | Value in the sample | Explanation |
|---|---|---|
| DSN (Data Source Name) | mysql:host=localhost;dbname=teacher;charset=utf8mb4 |
which database system, where it runs, which database, encoding (diacritics) |
| user | teacher |
as in Adminer |
| password | teacher_psw |
as in Adminer |
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION |
on an SQL error the script stops and prints the message. Without it the error disappears silently and the page is just blank. | |
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC |
every record arrives as an array whose key is the column name: $row['name'] |
Your own login details are from lab cv06. The teacher details are fictional, for the examples only.
Methods: ready-made commands PDO knows
PHP has ready-made methods for communicating through PDO: commands with a name that PDO knows and that we call as $pdo->name(...). We do not need to know how they are written inside. It is enough to know what each does and what it returns. For listings and inserts we combine them: one sends the SQL query and the next takes over the result the database returns.
We always keep the result in a variable. In all examples it is called $stmt (statement). It holds the SQL statement, prepared or already executed, and from it we then take the records.
| Method | What it does |
|---|---|
$stmt = $pdo->query('SQL'); |
sends finished SQL to the database, stores the result in $stmt |
$stmt = $pdo->prepare('SQL with ?'); |
prepares SQL with question marks, values are filled in in the next step |
$stmt->execute([values]); |
fills the values in for the question marks and sends the SQL to the database |
$rows = $stmt->fetchAll(); |
the result of the query is a table; every row of the table is an array |
$row = $stmt->fetch(); |
the result is one record, an array |
$stmt->rowCount() |
a number: how many records the statement changed |
$pdo->lastInsertId() |
a number: the id the database assigned to the last INSERT |
Prepare and execute: where the values are
The values that go into the database are in PHP variables. The simplest example, inserting one grade:
$name = $_POST['name']; // the user typed 7a
$value = $_POST['value']; // the user typed 7.0
$stmt = $pdo->prepare('INSERT INTO grades (name, value) VALUES (?, ?)'); // two question marks
$stmt->execute([$name, $value]); // the first ? gets $name, the second ? gets $value
In the prepare step the database receives the SQL with question marks and prepares it. In the execute step it receives the values, puts them in place of the question marks and executes the statement. The question mark is called a placeholder. There are exactly as many question marks as elements in the execute array, in the same order.
The rule: query or prepare
An SQL query is either written whole in the script and never changes, or a value from the user enters it: from a form or from the URL. That decides:
If the SQL contains no value from the user, we send it with query. If a value from the user enters the SQL, we use prepare with a question mark in place of the value and execute with the values.
| SQL | Where the value comes from | Method |
|---|---|---|
SELECT id, name FROM grades ORDER BY value |
no value from the user | query |
SELECT COUNT(*) FROM routes |
no value from the user | query |
SELECT name FROM routes WHERE grade_id = ? |
grade_id from the select in the filter, arrives in the URL | prepare + execute([$gradeId]) |
INSERT INTO grades (name, value) VALUES (?, ?) |
name and value come from the form, typed by the user, an injection risk |
prepare + execute([$name, $value]) |
INSERT INTO routes (name, holds, grade_id, since) VALUES (?, ?, ?, ?) |
every value comes from the form | prepare + execute([$name, $holds, $gradeId, $since]) |
SELECT * FROM routes WHERE id = ? |
id from the URL: in the route list you click “detail”, the URL is detail.php?id=2; you can rewrite the 2 in the address bar to anything |
prepare + execute([$id]) |
The database always reads values sent through execute as data, never as SQL. If the user types ' OR 1=1 into a form input, exactly that text is stored. If we paste the value into the SQL as text, the user can add their own SQL in the URL or in the input. That is SQL injection; we show it in example 7 on the route detail with a rewritten id. The query/prepare rule is the whole protection against it.
What the database returns
The database always returns one of three things:
- Yes or no. For INSERT the database returns whether the statement was executed.
executereturnstrueorfalse. In Adminer you saw it as the text “1 row affected”. - A number. For
SELECT COUNT(*)the result is one number.rowCount()(how many records changed) andlastInsertId()(id of the new record) also return a number. Here you print or read nothing from a table, the database returns the number directly. - Records. For SELECT the result is a table. In Adminer you saw it on the screen at once. In PHP the result lands in the server’s memory and does not get to the web without more code. We have to catch it into a variable and prepare what we print from it. That is what
fetchAllandfetchare for:
| Records in the result | Method | What is in the variable | When the database found nothing | How we print |
|---|---|---|---|---|
| several | $rows = $stmt->fetchAll(); |
a table: an array where every row is one record; a record is an array with column names | an empty array [], foreach prints nothing |
foreach ($rows as $row) { echo $row['name']; } |
| one | $row = $stmt->fetch(); |
one record, an array | false |
if ($row) { echo $row['name']; } |
When a number is useful instead of records:
$pdo->lastInsertId()after inserting into the main entity. The database assigned an id to the new record and we need that same id in the pivot table for every checked style.$stmt->rowCount()after INSERT as a check that one record was written. In cv08, with UPDATE and DELETE, it returns how many records changed.
Output from the database goes through htmlspecialchars
What we read from the database we print the same way as form values in week 6: through htmlspecialchars(). The database holds what someone wrote into it, including text with < and > tags.
Forms and the database
You know the form from week 6: an HTML form, PHP takes the values from $_POST into variables and checks them. Today we add one step after the check: prepare + execute, which writes the values. The examples follow the pages of the climbing wall application, in this order:
data.php(lookup tables): a listing of every table as it is, with ids and foreign keys, and forms to add a record to the lookup tables (grades, styles): one INSERT, a duplicate check withfetch,add-route.php(main entity, new record): a form for the main entity (routes) with the pivot table (route_styles): a select and checkboxes filled from the lookup tables, one INSERT,lastInsertId, then one INSERT per checked checkbox in aforeach,routes.php(main entity, list): the list from the database through a JOIN and a GET filter,detail.php(main entity, detail): a route by id from the URL, bad and good version (SQL injection),stats.php(overview): JOIN listings, the pivot table with names, counts withGROUP BY, one record withfetch.
Common errors and what they mean
Messages start with SQLSTATE[...]: that is the error code from the database, which PDO prints thanks to the ERRMODE_EXCEPTION setting.
| Message | Cause | Fix |
|---|---|---|
SQLSTATE[HY000] [1045] Access denied for user |
wrong user or password in db.php |
check the details from lab cv06 |
SQLSTATE[HY000] [1049] Unknown database |
wrong database name in the DSN | the database name is the same as the login name |
SQLSTATE[42S02] Base table or view not found |
the table does not exist or the name has a typo | run schema.sql in Adminer, check the name |
SQLSTATE[42S22] Unknown column |
typo in a column name | compare with schema.sql |
SQLSTATE[23000] ... foreign key constraint fails |
you are inserting an id that is not in the lookup table | the select in the form must have value = id from the database |
SQLSTATE[23000] ... Duplicate entry |
a UNIQUE value already exists | the same grade a second time is not inserted, which is the correct behaviour |
SQLSTATE[HY093] Invalid parameter number |
the number of ? does not match the number of values in execute |
count the question marks and the array elements |
Call to a member function fetchAll() on bool |
query() got wrong SQL and returned false |
try the SQL in Adminer; check that db.php has ERRMODE_EXCEPTION |
Trying to access array offset on false |
fetch() found nothing and you read $row['name'] |
if ($row) first |
Array to string conversion |
you are printing an array instead of an element | $row['name'], not $row |
Undefined array key "style" |
no checkbox was checked | $_POST['style'] ?? [] |
Undefined variable $pdo |
the page has no require 'db.php' |
add the require at the top of the page |
Deprecated: htmlspecialchars(): Passing null to parameter #1 |
a column without a value (optional note) is NULL in the database, not text |
htmlspecialchars($value ?? ''): ?? gives an empty text when the value is NULL (week 6) |
UkážkyExamples
Ukážky sú files aplikácie lezecká stena zo vzoru cv07. Stránku tvorí file stránky v web/ (pripojí db.php, nastaví $title, $active, $content a pripojí template.php) a content file v content/ s rovnakým názvom. template.php vypíše <h1> z $title, preto content files vlastný <h1> nemajú. Formuláre majú Bootstrap classes z cv05: form-label, form-control, form-select, form-check, btn. Pod každým kódom je náhľad stránky v prehliadači s adresou, ktorá sa otvorí, a pod SELECT to, čo vráti na dátach zo seed.sql. Odsek „Vo svojej aplikácii” hovorí, čo sa mení pre iné tables. Roly files a pravidlo ich názvov sú v týždni 9.
Ukážka 1: db.php a template.php, pripojenie a template
<?php
ini_set('display_errors', 1); // sigma má hlásenia chýb vypnuté; takto hlášky uvidíš (ako v týždni 5)
error_reporting(E_ALL); // zobraz všetky chyby
$dsn = 'mysql:host=localhost;dbname=teacher;charset=utf8mb4'; // kde je databáza, ktorá, kódovanie
$user = 'teacher'; // používateľ ako v Adminer
$password = 'teacher_psw'; // heslo ako v Adminer
$pdo = new PDO($dsn, $user, $password, [ // pripojenie; $pdo použijú všetky ďalšie files
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // chyba v SQL zastaví skript a vypíše hlášku
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // record = array s názvami columns
]);
Čo robí ktorý riadok: riadky ini_set a error_reporting zapnú zobrazenie chýb, bez nich je stránka s chybou na sigma.tuke.sk biela (týždeň 5). Riadky $dsn, $user a $password sú premenné s údajmi. new PDO(...) vytvorí pripojenie a uloží ho do $pdo. V hranatých zátvorkách sú nastavenia z tabuľky v teórii.
Takto to vyzerá v prehliadači: db.php otvorený priamo nevypíše nič, prázdna stránka je správne. Pri zlom hesle: Fatal error: Uncaught PDOException: SQLSTATE[HY000] [1045] Access denied for user 'teacher'@'localhost'.
Vo svojej aplikácii. V db.php sú prihlasovacie údaje z cvičenia cv06. V template.php je názov aplikácie a položky menu podľa svojich files.
<!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 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>
Čo sa zmenilo oproti cv05: v menu pribudli odkazy na add-route.php (main entity, nový record), data.php (lookup tables) a stats.php (prehľad) a odišiel odkaz na form.php. Registračný formulár z cv05 bol ukážka typov inputs, aplikácia ho nepoužíva. Všetko ostatné v template je rovnaké.
Ukážka 2: data.php (lookup tables), výpis každej table a INSERT do lookup tables
<?php
require 'db.php'; // pripojenie: content/data.php bude mať $pdo
$title = 'Databáza';
$active = 'data';
$content = 'content/data.php';
include 'template.php';
<?php
$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. Novú cestu pridáš na stránke <a href="add-route.php">Nová cesta</a>.</p>
<?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; ?>
</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; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php else: ?>
<p class="text-muted">Table je prázdna.</p>
<?php endif; ?>
<?php endforeach; ?>
Čo robí ktorý riadok: content/data.php má formulár pre grades a formulár pre styles a oba sa odosielajú na tú istú adresu data.php, preto má každý <input type="hidden" name="form"> a PHP podľa jeho hodnoty vie, ktorý bol odoslaný. Pri každom vkladaní je najprv SELECT ... WHERE name = ? a fetch(): keď vráti record, hodnota už existuje a INSERT sa nespustí; keď vráti false, nasleduje INSERT. rowCount() vráti 1, lebo sa zapísal jeden record. Výpis tables je jeden foreach cez názvy tables, v ňom foreach cez records a v ňom foreach cez columns; vďaka FETCH_ASSOC je record array a array_keys($rows[0]) dá názvy columns pre hlavičku. if ($rows) ošetrí prázdnu table: fetchAll vráti prázdny array.
Databáza
Nový grade
Pridať gradeNový style
Pridať stylegrades
SELECT * FROM grades
| id | name | value |
|---|---|---|
| 1 | 5a | 5.0 |
| 2 | 6a | 6.0 |
| 3 | 6b | 6.3 |
| 4 | 7a | 7.0 |
(pod tým rovnako tabuľky styles, routes a route_styles)
Takto to vyzerá v prehliadači: otvorená adresa je data.php. Hore sú vedľa seba formuláre Nový grade a Nový style, pod nimi tabuľky grades, styles, routes a route_styles, každá s nadpisom a SQL. Po odoslaní 7a a 7.0 je nad formulármi správa „Pridaný grade 7a (1 record).” a v tabuľke grades nový record. Po druhom odoslaní tých istých hodnôt je tam správa „Grade 7a už existuje.” Keby kontrola fetch() nebola, databáza by odmietla duplicitu chybou SQLSTATE[23000] ... Duplicate entry '7a', lebo name je UNIQUE.
Vo svojej aplikácii. Formulár a blok PHP pre každú svoju lookup table, s jej columns. V poli s názvami tables vo výpise sú názvy svojich tables.
Čo vráti SELECT * FROM routes (vidno grade_id, nie 5a; preto je v routes.php JOIN) a SELECT * FROM route_styles (len dvojice id):
| id | name | holds | grade_id | since | note |
|---|---|---|---|---|---|
| 1 | Žltá hrana | žlté | 1 | 2026-09-14 | Vhodná pre začiatočníkov. |
| 2 | Modrý previs | modré | 2 | 2026-09-21 | Previs s dobrými chytmi. |
| 3 | Červená platňa | červené | 3 | 2026-10-05 | Malé stupy, treba dobre stáť. |
| 4 | Zelená platňa | zelené | 1 | 2026-10-19 | Dlhá, vytrvalostná. |
| route_id | style_id |
|---|---|
| 1 | 1 |
| 2 | 1 |
| 2 | 2 |
Ukážka 3: add-route.php (main entity), INSERT do main entity a pivot table
<?php
require 'db.php';
$title = 'Nová cesta';
$active = 'add-route';
$content = 'content/add-route.php';
include 'template.php';
<?php
$message = '';
$grades = $pdo->query('SELECT id, name FROM grades ORDER BY value')->fetchAll(); // pre select; SQL bez hodnôt od používateľa: query
$styles = $pdo->query('SELECT id, name FROM styles ORDER BY name')->fetchAll(); // pre checkboxy
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = $_POST['name']; // najprv všetko z $_POST do premenných
$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('INSERT INTO routes (name, holds, grade_id, since, note) VALUES (?, ?, ?, ?, ?)');
$stmt->execute([$name, $holds, $gradeId, $since, $note]); // 1. INSERT: main entity
$routeId = $pdo->lastInsertId(); // id novej cesty, pridelila ho databáza
$stmt = $pdo->prepare('INSERT INTO route_styles (route_id, style_id) VALUES (?, ?)'); // prepare raz
foreach ($styleIds as $styleId) { // execute toľkokrát, koľko je zaškrtnuté
$stmt->execute([$routeId, $styleId]); // dvojica do pivot table
}
$message = 'Cesta ' . $name . ' pridaná, styles: ' . count($styleIds) . '. Pozri ju v zozname Cesty.';
}
}
?>
<?php if ($message !== ''): ?>
<div class="alert alert-info"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>
<form method="post" class="row g-3">
<div class="col-md-6">
<label class="form-label" for="name">Názov cesty</label>
<input class="form-control" id="name" name="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" 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>
<option value="">vyber</option>
<?php foreach ($grades as $grade): ?> <!-- jeden option na každý record -->
<option value="<?= $grade['id'] ?>"><?= htmlspecialchars($grade['name']) ?></option> <!-- value = id, text = name -->
<?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" 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"></textarea>
</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'] ?>"> <!-- style[]: do PHP príde array id -->
<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">Pridať cestu</button>
</div>
</form>
Čo robí ktorý riadok: select a checkboxy sa plnia z databázy dvoma query, lebo do SQL nevstupuje nič od používateľa; používateľ vidí názov, do PHP príde id (value). Po odoslaní ide najprv INSERT do main entity, potom lastInsertId() a vo foreach INSERT do pivot table pre každé zaškrtnuté id. prepare pre pivot table je pred foreach, execute vnútri. Zápis <?php foreach (...): ?> … <?php endforeach; ?> je ten istý foreach ako v týždni 5, len rozdelený okolo HTML.
Nová cesta
Takto to vyzerá v prehliadači: otvorená adresa je add-route.php, formulár je v dvoch stĺpcoch. Po odoslaní „Čierny kút, čierne, 6a, 2026-11-10, toprope + boulder” je nad formulárom správa „Cesta Čierny kút pridaná, styles: 2.” V data.php má routes nový record id 5 a route_styles dvojice (5, 1) a (5, 3). Poslali sa 3 príkazy: 1 INSERT do routes a 2 INSERT do route_styles. prepare pre pivot table sa zavolal raz, execute dvakrát. Pri žiadnom zaškrtnutom checkboxe je $styleIds prázdny array, foreach neprebehne a pošle sa 1 príkaz.
Vo svojej aplikácii. File stránky add-ENTITY.php a content file content/add-ENTITY.php. Select pre každý foreign key na lookup table, checkboxy pre pivot table, columns svojej main entity v INSERT.
Ukážka 4: routes.php (main entity), zoznam z databázy s filtrom cez GET
<?php
require 'db.php';
$title = 'Cesty';
$active = 'routes';
$content = 'content/routes.php';
include 'template.php';
<?php
$grades = $pdo->query('SELECT id, name FROM grades ORDER BY value')->fetchAll(); // pre select vo filtri
$gradeId = $_GET['grade'] ?? ''; // hodnota z URL; keď nie je, prázdny text
if ($gradeId === '') { // bez filtra: SQL bez hodnoty od používateľa
$stmt = $pdo->query('SELECT routes.id, routes.name, holds, grades.name AS grade, since
FROM routes JOIN grades ON routes.grade_id = grades.id
ORDER BY since DESC');
} else { // s filtrom: hodnota z URL, prepare
$stmt = $pdo->prepare('SELECT routes.id, routes.name, holds, grades.name AS grade, since
FROM routes JOIN grades ON routes.grade_id = grades.id
WHERE routes.grade_id = ?
ORDER BY since DESC');
$stmt->execute([$gradeId]);
}
$routes = $stmt->fetchAll(); // v oboch prípadoch tabuľka records
?>
<form method="get" class="row g-2 align-items-end mb-3"> <!-- GET: výber sa objaví v URL -->
<div class="col-auto">
<label class="form-label" for="grade">Grade</label>
<select class="form-select" id="grade" name="grade">
<option value="">všetky</option>
<?php foreach ($grades as $grade): ?>
<option value="<?= $grade['id'] ?>" <?= $grade['id'] == $gradeId ? 'selected' : '' ?>><?= htmlspecialchars($grade['name']) ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="col-auto"><button class="btn btn-primary">Filtrovať</button></div>
<div class="col-auto ms-auto"><a class="btn btn-outline-primary" href="add-route.php">Nová cesta</a></div>
</form>
<p>Ciest: <?= count($routes) ?></p>
<div class="row g-3">
<?php foreach ($routes as $route): ?> <!-- karty ako doteraz, dáta z databázy -->
<div class="col-md-4">
<div class="card h-100">
<div class="card-body">
<h2 class="card-title h5"><?= htmlspecialchars($route['name']) ?> <span class="badge text-bg-secondary"><?= htmlspecialchars($route['grade']) ?></span></h2>
<p class="card-text">Chyty: <?= htmlspecialchars($route['holds']) ?>, postavená <?= $route['since'] ?></p>
<a href="detail.php?id=<?= $route['id'] ?>" class="btn btn-outline-primary btn-sm">detail</a> <!-- id v URL, ukážka 5 -->
</div>
</div>
</div>
<?php endforeach; ?>
</div>
Čo robí ktorý riadok: $_GET['grade'] ?? '' prečíta hodnotu z URL; keď v URL nie je, dá prázdny text. Podľa toho sa vyberie query bez WHERE alebo prepare s WHERE. selected v option nechá vo filtri vybranú hodnotu aj po obnovení stránky. Statické karty z týždňov 4 až 6 sú zo súboru preč, HTML karty zostalo bez obrázka, zmenil sa zdroj dát. Fotky ciest nie sú súčasťou projektu, column photo z týždňa 7 vo vzore cv07 nie je.
Čo vráti SELECT bez filtra:
| id | name | holds | grade | since |
|---|---|---|---|---|
| 4 | Zelená platňa | zelené | 5a | 2026-10-19 |
| 3 | Červená platňa | červené | 6b | 2026-10-05 |
| 2 | Modrý previs | modré | 6a | 2026-09-21 |
| 1 | Žltá hrana | žlté | 5a | 2026-09-14 |
Cesty
Ciest: 2
Zelená platňa 5a
Chyty: zelené, postavená 2026-10-19
detailŽltá hrana 5a
Chyty: žlté, postavená 2026-09-14
detailTakto to vyzerá v prehliadači: otvorená adresa je routes.php. Hore je select „všetky”, tlačidlo Filtrovať a vpravo Nová cesta, pod nimi „Ciest: 4” a karty ako v týždni 4, teraz z databázy. Po výbere 5a sa URL zmení na routes.php?grade=1, vypíše „Ciest: 2”, Zelená platňa a Žltá hrana. URL sa dá uložiť do záložky a poslať: to je rozdiel GET oproti POST.
Vo svojej aplikácii. File stránky ENTITY.php a content file content/ENTITY.php. V SELECT sú columns svojej main entity a JOIN na svoju lookup table, filter je podľa jej id.
Ukážka 5: detail.php (main entity), record podľa id z URL, zlá a dobrá verzia
<?php
require 'db.php';
$title = 'Detail cesty';
$active = 'routes';
$content = 'content/detail.php';
include 'template.php';
<?php
$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.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-secondary btn-sm" href="routes.php">späť na zoznam</a>
Čo robí ktorý riadok: $_GET['id'] je hodnota z URL. Dobrá verzia ju pošle cez execute, databáza ju číta len ako číslo id. fetch() vráti jeden record alebo false; return v if zastaví zvyšok file, aby sa nevypísal prázdny detail. Druhý SELECT prejde pivot table a vráti styles tejto cesty, zasa cez prepare, lebo id je z URL.
Detail cesty
Modrý previs
Grade 6a, chyty modré, postavená 2026-09-21
Previs s dobrými chytmi.
Styles: toprope lead
späť na zoznam
Takto to vyzerá v prehliadači, v tomto poradí: (1) v routes.php klikneš na „detail” pri Modrom previse, URL je detail.php?id=2, zobrazí sa Modrý previs so styles toprope a lead. (2) V adresnom riadku prepíšeš id=2 na id=3: Červená platňa. Používateľ si vie hodnotu zmeniť a databáza ju dostane. (3) Keď je zapnutá zlá verzia a do URL dáš id=0 OR 1=1, SQL sa stane WHERE routes.id = 0 OR 1=1, čo platí pre každý record: vráti sa prvá cesta z celej table a s fetchAll by sa vrátili všetky. Používateľ si dopísal vlastné SQL. (4) Dobrá verzia s tou istou URL vypíše „Cesta sa nenašla.”, lebo 0 OR 1=1 je pre databázu hodnota, nie SQL. Z textu zoberie číslo na začiatku, 0, a cesta s id 0 nie je. Preto je v ukážke 0 a nie 1: pri 1 OR 1=1 by dobrá verzia vrátila cestu s id 1, čo je správne, ale na prednáške menej názorné.
Vo svojej aplikácii. detail.php s content/detail.php vypíše jeden record svojej main entity podľa id z URL a položky z pivot table druhým SELECT.
Ukážka 6: stats.php (prehľad), výpisy cez JOIN a počty
<?php
require 'db.php';
$title = 'Prehľad';
$active = 'stats';
$content = 'content/stats.php';
include 'template.php';
<?php
// Všetky SELECT sú cez query: do SQL nevstupuje nič od používateľa. Každé SQL je v premennej, aby sa dalo vypísať nad výsledkom.
$sqlRoutes = 'SELECT routes.name, holds, grades.name AS grade, since
FROM routes JOIN grades ON routes.grade_id = grades.id
ORDER BY since DESC'; // main entity s hodnotou z lookup table
$routes = $pdo->query($sqlRoutes)->fetchAll();
$sqlPairs = 'SELECT routes.name AS route, styles.name AS style
FROM route_styles
JOIN routes ON routes.id = route_styles.route_id
JOIN styles ON styles.id = route_styles.style_id
ORDER BY routes.name, styles.name'; // pivot table s názvami z oboch strán
$pairs = $pdo->query($sqlPairs)->fetchAll();
$sqlByGrade = 'SELECT grades.name AS grade, COUNT(*) AS routes_count
FROM routes JOIN grades ON routes.grade_id = grades.id
GROUP BY grades.name ORDER BY grades.name'; // počet podľa lookup table
$byGrade = $pdo->query($sqlByGrade)->fetchAll();
$sqlHardest = 'SELECT routes.name, grades.name AS grade
FROM routes JOIN grades ON routes.grade_id = grades.id
ORDER BY grades.value DESC, since LIMIT 1'; // jeden record: fetch
$hardest = $pdo->query($sqlHardest)->fetch();
$sqlNewest = 'SELECT name, since FROM routes ORDER BY since DESC LIMIT 1';
$newest = $pdo->query($sqlNewest)->fetch();
?>
<div class="row g-3 mb-4">
<div class="col-md-6">
<div class="card"><div class="card-body">
<h2 class="h6 text-muted">Najťažšia cesta</h2>
<?php if ($hardest): ?> <!-- false, keby nebola žiadna cesta -->
<p class="h4 mb-0"><?= htmlspecialchars($hardest['name']) ?> <span class="badge text-bg-secondary"><?= htmlspecialchars($hardest['grade']) ?></span></p>
<?php endif; ?>
<pre class="small mt-2 mb-0"><?= $sqlHardest ?></pre>
</div></div>
</div>
<div class="col-md-6">
<div class="card"><div class="card-body">
<h2 class="h6 text-muted">Najnovšia cesta</h2>
<?php if ($newest): ?>
<p class="h4 mb-0"><?= htmlspecialchars($newest['name']) ?> <small class="text-muted"><?= $newest['since'] ?></small></p>
<?php endif; ?>
<pre class="small mt-2 mb-0"><?= $sqlNewest ?></pre>
</div></div>
</div>
</div>
<h2 class="h5">Cesty s grade</h2>
<pre class="small"><?= $sqlRoutes ?></pre>
<table class="table table-sm table-striped">
<thead><tr><th>Cesta</th><th>Chyty</th><th>Grade</th><th>Postavená od</th></tr></thead>
<tbody>
<?php foreach ($routes as $route): ?>
<tr>
<td><?= htmlspecialchars($route['name']) ?></td>
<td><?= htmlspecialchars($route['holds']) ?></td>
<td><?= htmlspecialchars($route['grade']) ?></td>
<td><?= $route['since'] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<h2 class="h5 mt-4">Cesty a ich styles</h2>
<pre class="small"><?= $sqlPairs ?></pre>
<table class="table table-sm table-striped">
<thead><tr><th>Cesta</th><th>Style</th></tr></thead>
<tbody>
<?php foreach ($pairs as $pair): ?>
<tr><td><?= htmlspecialchars($pair['route']) ?></td><td><?= htmlspecialchars($pair['style']) ?></td></tr>
<?php endforeach; ?>
</tbody>
</table>
<h2 class="h5 mt-4">Počet ciest podľa grade</h2>
<pre class="small"><?= $sqlByGrade ?></pre>
<table class="table table-sm table-striped">
<thead><tr><th>Grade</th><th>Počet</th></tr></thead>
<tbody>
<?php foreach ($byGrade as $row): ?>
<tr><td><?= htmlspecialchars($row['grade']) ?></td><td><?= $row['routes_count'] ?></td></tr>
<?php endforeach; ?>
</tbody>
</table>
Čo robí ktorý riadok: SQL je v premenných $sqlRoutes, $sqlPairs, … len preto, aby sa dalo vypísať nad tabuľkou; query($sqlRoutes) je to isté ako query('SELECT ...'). SQL je to, čo si skúšal v cv06 v Adminer (queries.sql, dotazy 9, 10, 13 a 15), s AS, aby column vo výsledku mala jednoznačný názov pre $row['grade']. Pri jednom record je fetch() a if ($hardest), pri viacerých fetchAll() a foreach.
Čo vráti Cesty s grade:
| name | holds | grade | since |
|---|---|---|---|
| Zelená platňa | zelené | 5a | 2026-10-19 |
| Červená platňa | červené | 6b | 2026-10-05 |
| Modrý previs | modré | 6a | 2026-09-21 |
| Žltá hrana | žlté | 5a | 2026-09-14 |
Čo vráti Cesty a ich styles (Červená a Zelená nemajú style, vo výpise nie sú, lebo je to JOIN a nie LEFT JOIN):
| route | style |
|---|---|
| Modrý previs | lead |
| Modrý previs | toprope |
| Žltá hrana | toprope |
Čo vráti Počet ciest podľa grade: 5a 2, 6a 1, 6b 1. Najťažšia cesta: Červená platňa (6b); pri rovnakej value rozhodne since, preto je v ORDER BY druhé kritérium. Najnovšia: Zelená platňa 2026-10-19.
Takto to vyzerá v prehliadači: otvorená adresa je stats.php. Hore sú karty Najťažšia cesta a Najnovšia cesta, pod nimi tabuľky Cesty s grade, Cesty a ich styles a Počet ciest podľa grade, každá so svojím SQL.
Vo svojej aplikácii. stats.php s content/stats.php má SELECT s JOIN, pivot table s názvami, počet cez GROUP BY a jeden record cez fetch, každý nad svojimi tables.
Ukážka 7: prompty
Prompty A, B a C. Ku každému priložíš svoj sql/schema.sql, aby AI videla presné názvy tables a columns, a svoj template.php, aby stránky sedeli do aplikácie.
Prompt A, db.php a data.php (lookup tables):
Mám PHP web, kde každá stránka je file v web/ s premennými $title, $active, $content a include 'template.php' (priložený), obsah je v content/. Databáza MariaDB má tables podľa priloženého schema.sql. Napíš: 1. web/db.php s pripojením cez PDO, nastavenia ERRMODE_EXCEPTION a FETCH_ASSOC, DSN s charset=utf8mb4, na začiatku ini_set('display_errors', 1) a error_reporting(E_ALL), prihlasovacie údaje nechaj ako // DOPLŇ. 2. web/data.php (require 'db.php' pred include) a web/content/data.php: hore pre každú lookup table malý Bootstrap formulár na pridanie record (method POST, hidden input form s názvom table, hodnoty z $_POST do premenných, kontrola povinných, SELECT ... WHERE name = ? s fetch na kontrolu duplicity, potom INSERT cez prepare a execute s otáznikmi, hláška v alert); pod tým výpis každej table zo schema.sql tak, ako je (SELECT * cez query, SQL vypísané v pre nad tabuľkou, hlavička z array_keys prvého record, hodnoty cez htmlspecialchars). Žiadne funkcie ani triedy, PHP hore a HTML dole s foreach/endforeach, komentár pri každom riadku po slovensky.
Prompt B, add-ENTITY.php (main entity, nový record s pivot table):
Pre ten istý web (template.php a schema.sql priložené) napíš web/add-ENTITY.php a web/content/add-ENTITY.php: Bootstrap formulár method POST na pridanie record do main entity ENTITY. Premenná $pdo je pripravená v db.php. Pre foreign key na lookup table select naplnený z databázy (value = id, text = name), pre pivot table checkboxy name="X[]" naplnené z databázy. Po odoslaní: hodnoty z $_POST do premenných, kontrola povinných inputs, INSERT do main entity cez prepare a execute s otáznikmi, lastInsertId, potom INSERT do pivot table vo foreach cez jeden pripravený príkaz. Hláška v alert s počtom zaškrtnutých položiek. Validačné pravidlá nechaj ako // DOPLŇ. Bez funkcií a tried, komentár pri každom riadku.
Prompt C, ENTITY.php (main entity, zoznam), detail.php a stats.php:
Pre ten istý web (template.php, schema.sql a priložený content/ZOZNAM.php so statickými kartami): 1. prerob content/ZOZNAM.php tak, aby karty čítal z databázy cez PDO: SELECT s JOIN na lookup table, zoradené od najnovšieho; nad zoznam formulár method GET so selectom podľa lookup table a možnosťou všetky; keď je parameter v URL, prepare s WHERE ... = ?, inak query; HTML kariet zachovaj, zmeň len zdroj dát; pri každej karte odkaz detail.php?id=... 2. web/detail.php a content/detail.php: id z $_GET, jeden record cez prepare a fetch, keď neexistuje hláška a return; položky pivot table tohto record druhým SELECT cez prepare. 3. web/stats.php a content/stats.php: tabuľky main entity s hodnotami z lookup table, pivot table s názvami z oboch strán, počet podľa lookup table (GROUP BY), jeden record naj (ORDER BY ... LIMIT 1, fetch); SQL v premenných a vypísané v pre nad každou tabuľkou. Výstup cez htmlspecialchars, Bootstrap table a card, komentár pri každom zmenenom riadku.
Prečo sú prompty napísané práve takto:
- priložený
schema.sqlatemplate.phpnamiesto opisu: AI vidí presné názvy a stránky sedia do aplikácie, - „bez funkcií a tried”: držíme sa toho, čo vieme čítať a vysvetliť,
// DOPLŇnecháva rozhodnutie na teba: údaje do db.php a validačné pravidlá dopĺňa autor aplikácie,- „HTML kariet zachovaj, zmeň len zdroj dát” bráni AI prerobiť celý web,
- požiadavka na query vs prepare núti model dodržať pravidlo a ty si ho pri čítaní zopakuješ,
- „$pdo je pripravená v db.php”: AI nevloží druhé pripojenie do každého file,
- „SQL vypísané nad tabuľkou”: na obhajobe ukážeš príkaz aj výsledok na jednej obrazovke.
The examples are files of the climbing wall application from sample cv07. A page consists of the page file in web/ (includes db.php, sets $title, $active, $content and includes template.php) and the content file in content/ with the same name. template.php prints <h1> from $title, so content files have no <h1> of their own. Forms use the Bootstrap classes from cv05: form-label, form-control, form-select, form-check, btn. Under every piece of code is a preview of the page in the browser with the address that opens, and under a SELECT what it returns on the data from seed.sql. The paragraph “In your own application” says what changes for other tables. File roles and the naming rule are in week 9.
Example 1: db.php and template.php, connection and template
<?php
ini_set('display_errors', 1); // sigma má hlásenia chýb vypnuté; takto hlášky uvidíš (ako v týždni 5)
error_reporting(E_ALL); // zobraz všetky chyby
$dsn = 'mysql:host=localhost;dbname=teacher;charset=utf8mb4'; // kde je databáza, ktorá, kódovanie
$user = 'teacher'; // používateľ ako v Adminer
$password = 'teacher_psw'; // heslo ako v Adminer
$pdo = new PDO($dsn, $user, $password, [ // pripojenie; $pdo použijú všetky ďalšie files
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // chyba v SQL zastaví skript a vypíše hlášku
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // record = array s názvami columns
]);
What each line does: the lines ini_set and error_reporting switch on error display, without them an error page on sigma.tuke.sk is blank (week 5). The lines $dsn, $user and $password are variables with the details. new PDO(...) creates the connection and stores it in $pdo. The square brackets hold the settings from the table in the theory.
What it looks like in the browser: db.php opened directly prints nothing, a blank page is correct. With a wrong password: Fatal error: Uncaught PDOException: SQLSTATE[HY000] [1045] Access denied for user 'teacher'@'localhost'.
In your own application. db.php holds the login details from lab cv06. template.php has the name of the application and menu items matching your files.
<!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 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>
What changed since cv05: the menu gained links to add-route.php (main entity, new record), data.php (lookup tables) and stats.php (overview) and lost the link to form.php. The registration form from cv05 was a demonstration of input types; the application does not use it. Everything else in the template is the same.
Example 2: data.php (lookup tables), listing every table and INSERT into lookup tables
<?php
require 'db.php'; // pripojenie: content/data.php bude mať $pdo
$title = 'Databáza';
$active = 'data';
$content = 'content/data.php';
include 'template.php';
<?php
$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. Novú cestu pridáš na stránke <a href="add-route.php">Nová cesta</a>.</p>
<?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; ?>
</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; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php else: ?>
<p class="text-muted">Table je prázdna.</p>
<?php endif; ?>
<?php endforeach; ?>
What each line does: content/data.php has a form for grades and a form for styles and both submit to the same address data.php, so each has <input type="hidden" name="form"> and PHP tells from its value which one was submitted. Before every insert there is SELECT ... WHERE name = ? and fetch(): when it returns a record, the value already exists and the INSERT does not run; when it returns false, the INSERT follows. rowCount() returns 1 because one record was written. The table listing is one foreach over the table names, inside it a foreach over the records and inside that a foreach over the columns; thanks to FETCH_ASSOC a record is an array and array_keys($rows[0]) gives the column names for the header. if ($rows) handles an empty table: fetchAll returns an empty array.
Databáza
Nový grade
Pridať gradeNový style
Pridať stylegrades
SELECT * FROM grades
| id | name | value |
|---|---|---|
| 1 | 5a | 5.0 |
| 2 | 6a | 6.0 |
| 3 | 6b | 6.3 |
| 4 | 7a | 7.0 |
(pod tým rovnako tabuľky styles, routes a route_styles)
What it looks like in the browser: the opened address is data.php. At the top are the forms Nový grade and Nový style side by side, below them the tables grades, styles, routes and route_styles, each with a heading and the SQL. After submitting 7a and 7.0 the message “Pridaný grade 7a (1 record).” is above the forms and the grades table has a new record. After submitting the same values again the message “Grade 7a už existuje.” Without the fetch() check the database would refuse the duplicate with the error SQLSTATE[23000] ... Duplicate entry '7a', because name is UNIQUE.
In your own application. A form and a PHP block for each of your lookup tables, with its columns. The array of table names in the listing holds the names of your tables.
What SELECT * FROM routes returns (you see grade_id, not 5a; hence the JOIN in routes.php) and SELECT * FROM route_styles (only id pairs):
| id | name | holds | grade_id | since | note |
|---|---|---|---|---|---|
| 1 | Žltá hrana | žlté | 1 | 2026-09-14 | Vhodná pre začiatočníkov. |
| 2 | Modrý previs | modré | 2 | 2026-09-21 | Previs s dobrými chytmi. |
| 3 | Červená platňa | červené | 3 | 2026-10-05 | Malé stupy, treba dobre stáť. |
| 4 | Zelená platňa | zelené | 1 | 2026-10-19 | Dlhá, vytrvalostná. |
| route_id | style_id |
|---|---|
| 1 | 1 |
| 2 | 1 |
| 2 | 2 |
Example 3: add-route.php (main entity), INSERT into the main entity and the pivot table
<?php
require 'db.php';
$title = 'Nová cesta';
$active = 'add-route';
$content = 'content/add-route.php';
include 'template.php';
<?php
$message = '';
$grades = $pdo->query('SELECT id, name FROM grades ORDER BY value')->fetchAll(); // pre select; SQL bez hodnôt od používateľa: query
$styles = $pdo->query('SELECT id, name FROM styles ORDER BY name')->fetchAll(); // pre checkboxy
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = $_POST['name']; // najprv všetko z $_POST do premenných
$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('INSERT INTO routes (name, holds, grade_id, since, note) VALUES (?, ?, ?, ?, ?)');
$stmt->execute([$name, $holds, $gradeId, $since, $note]); // 1. INSERT: main entity
$routeId = $pdo->lastInsertId(); // id novej cesty, pridelila ho databáza
$stmt = $pdo->prepare('INSERT INTO route_styles (route_id, style_id) VALUES (?, ?)'); // prepare raz
foreach ($styleIds as $styleId) { // execute toľkokrát, koľko je zaškrtnuté
$stmt->execute([$routeId, $styleId]); // dvojica do pivot table
}
$message = 'Cesta ' . $name . ' pridaná, styles: ' . count($styleIds) . '. Pozri ju v zozname Cesty.';
}
}
?>
<?php if ($message !== ''): ?>
<div class="alert alert-info"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>
<form method="post" class="row g-3">
<div class="col-md-6">
<label class="form-label" for="name">Názov cesty</label>
<input class="form-control" id="name" name="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" 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>
<option value="">vyber</option>
<?php foreach ($grades as $grade): ?> <!-- jeden option na každý record -->
<option value="<?= $grade['id'] ?>"><?= htmlspecialchars($grade['name']) ?></option> <!-- value = id, text = name -->
<?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" 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"></textarea>
</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'] ?>"> <!-- style[]: do PHP príde array id -->
<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">Pridať cestu</button>
</div>
</form>
What each line does: the select and the checkboxes are filled from the database with two query calls, because nothing from the user enters the SQL; the user sees the name, PHP receives the id (value). After submitting, first the INSERT into the main entity, then lastInsertId(), then in the foreach an INSERT into the pivot table for every checked id. prepare for the pivot table is before the foreach, execute inside. The notation <?php foreach (...): ?> … <?php endforeach; ?> is the same foreach as in week 5, only split around the HTML.
Nová cesta
What it looks like in the browser: the opened address is add-route.php, the form has two columns. After submitting “Čierny kút, čierne, 6a, 2026-11-10, toprope + boulder” the message “Cesta Čierny kút pridaná, styles: 2.” In data.php routes has a new record id 5 and route_styles the pairs (5, 1) and (5, 3). 3 statements were sent: 1 INSERT into routes and 2 INSERT into route_styles. prepare for the pivot table was called once, execute twice. With no checkbox checked $styleIds is an empty array, the foreach does not run and 1 statement is sent.
In your own application. A page file add-ENTITY.php and a content file content/add-ENTITY.php. A select for every foreign key to a lookup table, checkboxes for the pivot table, the columns of your main entity in the INSERT.
Example 4: routes.php (main entity), the list from the database with a GET filter
<?php
require 'db.php';
$title = 'Cesty';
$active = 'routes';
$content = 'content/routes.php';
include 'template.php';
<?php
$grades = $pdo->query('SELECT id, name FROM grades ORDER BY value')->fetchAll(); // pre select vo filtri
$gradeId = $_GET['grade'] ?? ''; // hodnota z URL; keď nie je, prázdny text
if ($gradeId === '') { // bez filtra: SQL bez hodnoty od používateľa
$stmt = $pdo->query('SELECT routes.id, routes.name, holds, grades.name AS grade, since
FROM routes JOIN grades ON routes.grade_id = grades.id
ORDER BY since DESC');
} else { // s filtrom: hodnota z URL, prepare
$stmt = $pdo->prepare('SELECT routes.id, routes.name, holds, grades.name AS grade, since
FROM routes JOIN grades ON routes.grade_id = grades.id
WHERE routes.grade_id = ?
ORDER BY since DESC');
$stmt->execute([$gradeId]);
}
$routes = $stmt->fetchAll(); // v oboch prípadoch tabuľka records
?>
<form method="get" class="row g-2 align-items-end mb-3"> <!-- GET: výber sa objaví v URL -->
<div class="col-auto">
<label class="form-label" for="grade">Grade</label>
<select class="form-select" id="grade" name="grade">
<option value="">všetky</option>
<?php foreach ($grades as $grade): ?>
<option value="<?= $grade['id'] ?>" <?= $grade['id'] == $gradeId ? 'selected' : '' ?>><?= htmlspecialchars($grade['name']) ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="col-auto"><button class="btn btn-primary">Filtrovať</button></div>
<div class="col-auto ms-auto"><a class="btn btn-outline-primary" href="add-route.php">Nová cesta</a></div>
</form>
<p>Ciest: <?= count($routes) ?></p>
<div class="row g-3">
<?php foreach ($routes as $route): ?> <!-- karty ako doteraz, dáta z databázy -->
<div class="col-md-4">
<div class="card h-100">
<div class="card-body">
<h2 class="card-title h5"><?= htmlspecialchars($route['name']) ?> <span class="badge text-bg-secondary"><?= htmlspecialchars($route['grade']) ?></span></h2>
<p class="card-text">Chyty: <?= htmlspecialchars($route['holds']) ?>, postavená <?= $route['since'] ?></p>
<a href="detail.php?id=<?= $route['id'] ?>" class="btn btn-outline-primary btn-sm">detail</a> <!-- id v URL, ukážka 5 -->
</div>
</div>
</div>
<?php endforeach; ?>
</div>
What each line does: $_GET['grade'] ?? '' reads the value from the URL; when the URL has none, it gives an empty text. That chooses query without WHERE or prepare with WHERE. selected on the option keeps the chosen value in the filter after the page reloads. The static cards from weeks 4 to 6 are gone from the file, the card HTML stayed without the image, the data source changed. Route photos are not part of the project; the photo column from week 7 is not in the cv07 sample.
What the SELECT without a filter returns:
| id | name | holds | grade | since |
|---|---|---|---|---|
| 4 | Zelená platňa | zelené | 5a | 2026-10-19 |
| 3 | Červená platňa | červené | 6b | 2026-10-05 |
| 2 | Modrý previs | modré | 6a | 2026-09-21 |
| 1 | Žltá hrana | žlté | 5a | 2026-09-14 |
Cesty
Ciest: 2
Zelená platňa 5a
Chyty: zelené, postavená 2026-10-19
detailŽltá hrana 5a
Chyty: žlté, postavená 2026-09-14
detailWhat it looks like in the browser: the opened address is routes.php. At the top a select “všetky” (all), the Filter button and New route on the right, below them “Ciest: 4” and the cards as in week 4, now from the database. After choosing 5a the URL changes to routes.php?grade=1, it prints “Ciest: 2”, Zelená platňa and Žltá hrana. The URL can be bookmarked and sent: that is the difference between GET and POST.
In your own application. A page file ENTITY.php and a content file content/ENTITY.php. The SELECT has the columns of your main entity and a JOIN to your lookup table; the filter uses its id.
Example 5: detail.php (main entity), a record by id from the URL, bad and good version
<?php
require 'db.php';
$title = 'Detail cesty';
$active = 'routes';
$content = 'content/detail.php';
include 'template.php';
<?php
$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.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-secondary btn-sm" href="routes.php">späť na zoznam</a>
What each line does: $_GET['id'] is the value from the URL. The good version sends it through execute, the database reads it only as an id number. fetch() returns one record or false; return in the if stops the rest of the file so that an empty detail is not printed. The second SELECT goes through the pivot table and returns the styles of this route, again through prepare, because the id is from the URL.
Detail cesty
Modrý previs
Grade 6a, chyty modré, postavená 2026-09-21
Previs s dobrými chytmi.
Styles: toprope lead
späť na zoznam
What it looks like in the browser, in this order: (1) in routes.php you click “detail” on Modrý previs, the URL is detail.php?id=2, Modrý previs is shown with the styles toprope and lead. (2) In the address bar you rewrite id=2 to id=3: Červená platňa. The user can change the value and the database receives it. (3) With the bad version switched on and id=0 OR 1=1 in the URL, the SQL becomes WHERE routes.id = 0 OR 1=1, which is true for every record: the first route of the whole table is returned, and with fetchAll all of them would be. The user added their own SQL. (4) The good version with the same URL prints “Cesta sa nenašla.” (route not found), because 0 OR 1=1 is a value to the database, not SQL. It takes the number at the start of the text, 0, and there is no route with id 0. That is why the example uses 0 and not 1: with 1 OR 1=1 the good version would return the route with id 1, which is correct but less telling at the lecture.
In your own application. detail.php with content/detail.php prints one record of your main entity by id from the URL and the items from the pivot table with a second SELECT.
Example 6: stats.php (overview), JOIN listings and counts
<?php
require 'db.php';
$title = 'Prehľad';
$active = 'stats';
$content = 'content/stats.php';
include 'template.php';
<?php
// Všetky SELECT sú cez query: do SQL nevstupuje nič od používateľa. Každé SQL je v premennej, aby sa dalo vypísať nad výsledkom.
$sqlRoutes = 'SELECT routes.name, holds, grades.name AS grade, since
FROM routes JOIN grades ON routes.grade_id = grades.id
ORDER BY since DESC'; // main entity s hodnotou z lookup table
$routes = $pdo->query($sqlRoutes)->fetchAll();
$sqlPairs = 'SELECT routes.name AS route, styles.name AS style
FROM route_styles
JOIN routes ON routes.id = route_styles.route_id
JOIN styles ON styles.id = route_styles.style_id
ORDER BY routes.name, styles.name'; // pivot table s názvami z oboch strán
$pairs = $pdo->query($sqlPairs)->fetchAll();
$sqlByGrade = 'SELECT grades.name AS grade, COUNT(*) AS routes_count
FROM routes JOIN grades ON routes.grade_id = grades.id
GROUP BY grades.name ORDER BY grades.name'; // počet podľa lookup table
$byGrade = $pdo->query($sqlByGrade)->fetchAll();
$sqlHardest = 'SELECT routes.name, grades.name AS grade
FROM routes JOIN grades ON routes.grade_id = grades.id
ORDER BY grades.value DESC, since LIMIT 1'; // jeden record: fetch
$hardest = $pdo->query($sqlHardest)->fetch();
$sqlNewest = 'SELECT name, since FROM routes ORDER BY since DESC LIMIT 1';
$newest = $pdo->query($sqlNewest)->fetch();
?>
<div class="row g-3 mb-4">
<div class="col-md-6">
<div class="card"><div class="card-body">
<h2 class="h6 text-muted">Najťažšia cesta</h2>
<?php if ($hardest): ?> <!-- false, keby nebola žiadna cesta -->
<p class="h4 mb-0"><?= htmlspecialchars($hardest['name']) ?> <span class="badge text-bg-secondary"><?= htmlspecialchars($hardest['grade']) ?></span></p>
<?php endif; ?>
<pre class="small mt-2 mb-0"><?= $sqlHardest ?></pre>
</div></div>
</div>
<div class="col-md-6">
<div class="card"><div class="card-body">
<h2 class="h6 text-muted">Najnovšia cesta</h2>
<?php if ($newest): ?>
<p class="h4 mb-0"><?= htmlspecialchars($newest['name']) ?> <small class="text-muted"><?= $newest['since'] ?></small></p>
<?php endif; ?>
<pre class="small mt-2 mb-0"><?= $sqlNewest ?></pre>
</div></div>
</div>
</div>
<h2 class="h5">Cesty s grade</h2>
<pre class="small"><?= $sqlRoutes ?></pre>
<table class="table table-sm table-striped">
<thead><tr><th>Cesta</th><th>Chyty</th><th>Grade</th><th>Postavená od</th></tr></thead>
<tbody>
<?php foreach ($routes as $route): ?>
<tr>
<td><?= htmlspecialchars($route['name']) ?></td>
<td><?= htmlspecialchars($route['holds']) ?></td>
<td><?= htmlspecialchars($route['grade']) ?></td>
<td><?= $route['since'] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<h2 class="h5 mt-4">Cesty a ich styles</h2>
<pre class="small"><?= $sqlPairs ?></pre>
<table class="table table-sm table-striped">
<thead><tr><th>Cesta</th><th>Style</th></tr></thead>
<tbody>
<?php foreach ($pairs as $pair): ?>
<tr><td><?= htmlspecialchars($pair['route']) ?></td><td><?= htmlspecialchars($pair['style']) ?></td></tr>
<?php endforeach; ?>
</tbody>
</table>
<h2 class="h5 mt-4">Počet ciest podľa grade</h2>
<pre class="small"><?= $sqlByGrade ?></pre>
<table class="table table-sm table-striped">
<thead><tr><th>Grade</th><th>Počet</th></tr></thead>
<tbody>
<?php foreach ($byGrade as $row): ?>
<tr><td><?= htmlspecialchars($row['grade']) ?></td><td><?= $row['routes_count'] ?></td></tr>
<?php endforeach; ?>
</tbody>
</table>
What each line does: the SQL is in the variables $sqlRoutes, $sqlPairs, … only so that it can be printed above the table; query($sqlRoutes) is the same as query('SELECT ...'). The SQL is what you tried in cv06 in Adminer (queries.sql, queries 9, 10, 13 and 15), with AS so that the result column has an unambiguous name for $row['grade']. For one record fetch() and if ($hardest), for several fetchAll() and foreach.
What Routes with grade returns:
| name | holds | grade | since |
|---|---|---|---|
| Zelená platňa | zelené | 5a | 2026-10-19 |
| Červená platňa | červené | 6b | 2026-10-05 |
| Modrý previs | modré | 6a | 2026-09-21 |
| Žltá hrana | žlté | 5a | 2026-09-14 |
What Routes and their styles returns (Červená and Zelená have no style, so they are not listed, because it is a JOIN and not a LEFT JOIN):
| route | style |
|---|---|
| Modrý previs | lead |
| Modrý previs | toprope |
| Žltá hrana | toprope |
What Routes per grade returns: 5a 2, 6a 1, 6b 1. The hardest route: Červená platňa (6b); with equal value the since decides, which is why ORDER BY has a second criterion. The newest: Zelená platňa 2026-10-19.
What it looks like in the browser: the opened address is stats.php. At the top are the cards Najťažšia cesta (hardest route) and Najnovšia cesta (newest route), below them the tables Cesty s grade, Cesty a ich styles and Počet ciest podľa grade, each with its SQL.
In your own application. stats.php with content/stats.php has a SELECT with JOIN, the pivot table with names, a count with GROUP BY and one record through fetch, each over your tables.
Example 7: prompts
Prompts A, B and C. Attach your sql/schema.sql to each, so that the AI sees the exact table and column names, and your template.php, so that the pages fit the application.
Prompt A, db.php and data.php (lookup tables):
I have a PHP site where every page is a file in web/ with the variables $title, $active, $content and include 'template.php' (attached); the content is in content/. The MariaDB database has the tables in the attached schema.sql. Write: 1. web/db.php with a PDO connection, settings ERRMODE_EXCEPTION and FETCH_ASSOC, a DSN with charset=utf8mb4, ini_set('display_errors', 1) and error_reporting(E_ALL) at the top, login details left as // TODO. 2. web/data.php (require 'db.php' before the include) and web/content/data.php: at the top, for every lookup table a small Bootstrap form to add a record (method POST, a hidden input form with the table name, values from $_POST into variables, a check of required inputs, SELECT ... WHERE name = ? with fetch to check duplicates, then INSERT through prepare and execute with question marks, a message in an alert); below it a listing of every table from schema.sql as it is (SELECT * through query, the SQL printed in a pre above the table, the header from array_keys of the first record, values through htmlspecialchars). No functions or classes, PHP at the top and HTML below with foreach/endforeach, a comment on every line.
Prompt B, add-ENTITY.php (main entity, new record with the pivot table):
For the same site (template.php and schema.sql attached) write web/add-ENTITY.php and web/content/add-ENTITY.php: a Bootstrap form, method POST, to add a record to the main entity ENTITY. The variable $pdo is prepared in db.php. For the foreign key to a lookup table a select filled from the database (value = id, text = name), for the pivot table checkboxes name="X[]" filled from the database. After submitting: values from $_POST into variables, a check of required inputs, INSERT into the main entity through prepare and execute with question marks, lastInsertId, then INSERT into the pivot table in a foreach through one prepared statement. A message in an alert with the number of checked items. Leave the validation rules as // TODO. No functions or classes, a comment on every line.
Prompt C, ENTITY.php (main entity, list), detail.php and stats.php:
For the same site (template.php, schema.sql and the attached content/LIST.php with static cards): 1. rework content/LIST.php so the cards are read from the database through PDO: SELECT with a JOIN to the lookup table, newest first; above the list a form method GET with a select by the lookup table and an option all; when the parameter is in the URL use prepare with WHERE ... = ?, otherwise query; keep the card HTML, change only the data source; on every card a link detail.php?id=... 2. web/detail.php and content/detail.php: id from $_GET, one record through prepare and fetch, a message and return when it does not exist; the pivot table items of this record with a second SELECT through prepare. 3. web/stats.php and content/stats.php: tables of the main entity with values from the lookup table, the pivot table with names from both sides, counts per lookup table (GROUP BY), one "most" record (ORDER BY ... LIMIT 1, fetch); the SQL in variables and printed in a pre above every table. Output through htmlspecialchars, Bootstrap table and card, a comment on every changed line.
Why the prompts are written this way:
- the attached
schema.sqlandtemplate.phpinstead of a description: the AI sees exact names and the pages fit the application, - “no functions or classes”: we stay with what we can read and explain,
// TODOleaves the decision to you: the author of the application fills in the details in db.php and the validation rules,- “keep the card HTML, change only the data source” stops the AI from rebuilding the whole site,
- the query vs prepare requirement makes the model follow the rule and you repeat it while reading,
- “$pdo is prepared in db.php”: the AI will not put a second connection into every file,
- “the SQL printed above the table”: at the defence you show the statement and its result on one screen.
Úlohy na cvičenieLab tasks
Prijať zadanie cv07 v Classroom 50 (platí pre skupiny B. Stehlíkovej; ostatné skupiny dostanú link od svojho cvičiaceho).
Výsledkom týždňa je aplikácia, nie cvičné files: každá položka menu niekam vedie a všetko číta zo svojej databázy. ENTITY je názov table svojej main entity.
8.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.
8.2 git clone repository cv07. Prekopíruj web/ z cv05 (cv06 obsahoval len SQL) a SQL files z cv06:
rsync -a --exclude .git cv05/ cv07/
mkdir -p cv07/sql
cp cv06/*.sql cv07/sql/
V Adminer spusti schema.sql a potom seed.sql, aby si začínal z čistých dát. Priečinok practice/ aplikácia nepoužíva, zmaže sa pri unifikácii v cv08.
8.3 web/db.php: pripojenie so svojimi údajmi z cv06 (prompt A alebo ukážka 1). Over v prehliadači: prázdna stránka bez hlášky.
8.4 data.php (lookup tables), teda web/data.php + content/data.php: výpis každej svojej table tak, ako je, s id a foreign keys, so SQL nad tabuľkou (prompt A alebo ukážka 2). Pridaj ju do menu v template.php.
8.5 Do content/data.php doplň formulár na pridanie record pre každú svoju lookup table (prepare, execute, kontrola duplicity cez fetch). Skús pridať hodnotu, ktorá už existuje, a do komentára v content/data.php napíš, čo by databáza vrátila bez tejto kontroly a prečo.
8.6 add-ENTITY.php (main entity, nový record), teda web/add-ENTITY.php + content/add-ENTITY.php: Bootstrap formulár na pridanie record do main entity vrátane pivot table (prompt B alebo ukážka 3). Select a checkboxy sa plnia z databázy. Do komentára na začiatok file napíš, koľko INSERT príkazov sa pošle pri dvoch zaškrtnutých checkboxoch. Over v data.php, že record je v main entity aj dvojice v pivot table.
8.7 ENTITY.php (main entity, zoznam; vo vzore routes.php + content/routes.php): karty z databázy cez JOIN, filter method="get" podľa jednej lookup table, odkaz na add-ENTITY.php (prompt C alebo ukážka 4). Statické dáta z týždňov 4 až 6 zo súboru zmaž. Over, že po výbere sa zmení URL aj výpis.
8.8 Detail (web/detail.php + content/detail.php): jeden record podľa id z URL cez prepare a fetch, odkaz „detail” pri každej karte, položky pivot table druhým SELECT (ukážka 5). Zlú verziu nechaj v komentári a do komentára napíš URL, ktorá by v zlej verzii vrátila všetko.
8.9 stats.php (prehľad), teda web/stats.php + content/stats.php: main entity s hodnotami z lookup table (JOIN), pivot table s názvami z oboch strán, počet records podľa lookup table (GROUP BY), jeden record „naj” (fetch); SQL vypísané nad každou tabuľkou (prompt C alebo ukážka 6). Pridaj do menu.
8.10 Menu v template.php má odkazy na index.php, ENTITY.php, add-ENTITY.php, data.php, stats.php a contact.php. Odkaz na registračný formulár z cv05 z menu odstráň; file sa zmaže pri unifikácii v cv08.
8.11 Commit a push, aspoň 4 commity v rôznych krokoch (napr. po 8.4, 8.6, 8.7, 8.9).
8.12 Upload Folder: cv07 do ti/cv07/ a obsah web/ do ti/projekt/. Over vo svojom webovom priestore na sigma.tuke.sk: každá položka menu funguje, zoznam číta z databázy, filter mení URL aj výpis, formuláre zapisujú, detail sa otvára podľa id.
Hodnotenie: 1 bod. Aplikácia so zoznamom z databázy a filtrom, detailom podľa id, formulárom na main entity s pivot table, data.php s formulármi na lookup tables a stats.php 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 cv07 in Classroom 50 (applies to B. Stehlíková’s groups; other groups get the link from their own teacher).
The result of the week is an application, not practice files: every menu item leads somewhere and everything reads from your own database. ENTITY is the name of the table of your main entity.
8.1 Kubeflow: check the extensions (SFTP, Five Server, Intelephense). If they are missing, run the restore command from guide 04 Submitting in the terminal.
8.2 git clone repository cv07. Copy web/ from cv05 (cv06 held only SQL) and the SQL files from cv06:
rsync -a --exclude .git cv05/ cv07/
mkdir -p cv07/sql
cp cv06/*.sql cv07/sql/
In Adminer run schema.sql and then seed.sql, so that you start from clean data. The application does not use the practice/ folder; it is deleted during the unification in cv08.
8.3 web/db.php: the connection with your details from cv06 (prompt A or example 1). Check in the browser: a blank page without a message.
8.4 data.php (lookup tables), that is web/data.php + content/data.php: a listing of every table of yours as it is, with ids and foreign keys, with the SQL above the table (prompt A or example 2). Add it to the menu in template.php.
8.5 In content/data.php add a form to add a record for every lookup table of yours (prepare, execute, a duplicate check with fetch). Try adding a value that already exists and write in a comment in content/data.php what the database would return without this check and why.
8.6 add-ENTITY.php (main entity, new record), that is web/add-ENTITY.php + content/add-ENTITY.php: a Bootstrap form that adds a record to the main entity including the pivot table (prompt B or example 3). The select and the checkboxes are filled from the database. In a comment at the top of the file write how many INSERT statements are sent with two checked checkboxes. Check in data.php that the record is in the main entity and the pairs in the pivot table.
8.7 ENTITY.php (main entity, list; in the sample routes.php + content/routes.php): cards from the database through a JOIN, a method="get" filter by one lookup table, a link to add-ENTITY.php (prompt C or example 4). Delete the static data from weeks 4 to 6 from the file. Check that after choosing, both the URL and the listing change.
8.8 The detail (web/detail.php + content/detail.php): one record by id from the URL through prepare and fetch, a “detail” link on every card, the pivot table items with a second SELECT (example 5). Leave the bad version in a comment and write in a comment the URL that would return everything in the bad version.
8.9 stats.php (overview), that is web/stats.php + content/stats.php: the main entity with values from the lookup table (JOIN), the pivot table with names from both sides, the number of records per lookup table (GROUP BY), one “most” record (fetch); the SQL printed above every table (prompt C or example 6). Add it to the menu.
8.10 The menu in template.php has links to index.php, ENTITY.php, add-ENTITY.php, data.php, stats.php and contact.php. Remove the link to the registration form from cv05 from the menu; the file is deleted during the unification in cv08.
8.11 Commit and push, at least 4 commits at different steps (e.g. after 8.4, 8.6, 8.7, 8.9).
8.12 Upload Folder: cv07 into ti/cv07/ and the content of web/ into ti/projekt/. Check in your web space on sigma.tuke.sk: every menu item works, the list reads from the database, the filter changes the URL and the listing, the forms write, the detail opens by id.
Grading: 1 point. The application with the list from the database and a filter, the detail by id, the form for the main entity with the pivot table, data.php with forms for the lookup tables and stats.php 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, the 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 cv07/ 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.
Vysvetli (code walkthrough)
- Čo je v DSN a čo sa stane, keď je zlý názov databázy.
- Čo robí ERRMODE_EXCEPTION a ako vyzerá stránka bez neho pri chybe.
- Čo robí FETCH_ASSOC a ako potom pristupuješ k hodnote column.
- Kedy stačí
querya kedy musí byťprepare; na konkrétnom riadku svojho kódu ukáž príklad oboch. - Čo je placeholder
?a čo musí sedieť s počtom otáznikov. - Prečo
preparezastaví SQL injection; čo databáza urobí s textom zexecute. - Ukáž v
content/detail.php, ktorý riadok v zlej verzii je nebezpečný a prečo. - Čo vráti
fetchAlla čofetch; ukáž, kde máš každé. Čo vráti každé, keď databáza nič nenašla. - Na čo je
lastInsertIda čo by sa stalo bez neho pri zápise do pivot table. - Koľko INSERT sa pošle pri zápise record s troma zaškrtnutými položkami pivot table a prečo.
- Prečo má checkbox
name="x[]"a čo je v$_POST['x']. - Prečo je
preparepredforeachaexecutevoforeach, nie oboje vnútri. - Ako select vo formulári získal svoje
<option>a prečo jevalueid, nie name. - V
content/data.php: ako PHP vie, ktorý formulár bol odoslaný. - V
content/data.php: čo robíSELECT id ... WHERE name = ?pred INSERT a čo by sa stalo bez neho. - V
content/data.php: čo vypíšearray_keys($rows[0])a prečo je okolo tabuľkyif ($rows). - Čo vráti JOIN výpis v
ENTITY.phpa prečo nestačíSELECT * FROM main_entity. - Ako funguje GET filter: čo je v URL, čo v
$_GET, ktorý SELECT sa vykoná pri prázdnom výbere. - Prečo hodnotu z databázy vypisuješ cez
htmlspecialchars, keď ju do databázy zapísala aplikácia. - Čo znamená hláška
foreign key constraint failspri formulári vadd-ENTITY.phpa ako k nej môže dôjsť. - Prečo má stránka
require 'db.php'vo file stránky vweb/a content file už$pdolen používa.
Uprav (live coding)
- Do tabuľky v
stats.phppridaj ďalšiu column z lookup table (vo vzoregrades.value). - Zmeň zoradenie zoznamu na inú column a opačný smer.
- Vo filtri pridaj druhú možnosť výberu (podľa inej column alebo lookup table); stačí SELECT a
?. - Vypíš pod zoznamom počet zobrazených records (
count($rows)), ak tam ešte nie je. - Vo formulári v
add-ENTITY.phpurob jedno nepovinné input povinným a ukáž hlášku. - Zmeň „naj” výpis z najväčšieho na najmenšie.
- Do
stats.phppridaj tabuľku: records lookup table, ktoré nemá žiadny record main entity (LEFT JOIN + IS NULL). - V
content/detail.phpzapni zlú verziu, ukáž útočnú URL, potom ju vráť na prepare a ukáž, že tá istá URL už nič nevráti. - V
data.phpzmeň poradie tables vo výpise alebo pridajORDER BYdo jedného SELECT. - Vo formulári v
add-ENTITY.phppridaj do selectu prvú položku „vyber” s prázdnymvaluea ošetri ju vo validácii, ak tam ešte nie je.
Zdôvodni (design decisions)
- Prečo je pripojenie v jednom file s
requirea nie v každom file znova. - Prečo sa filter posiela cez GET a formuláre na pridanie cez POST.
- Prečo select vo formulári plníš z databázy, a nie napísaný v HTML.
- Prečo nepoužívame spôsoby, ktoré vlepujú hodnoty do SQL, hoci existujú.
- Prečo si zvolil práve túto lookup table pre filter (čo chce používateľ v
ENTITY.phphľadať). - Prečo sú formuláre na lookup tables v
data.phppri výpise a formulár na main entity má vlastnú stránkuadd-ENTITY.php.
Definition of Done
db.phppripojí bez hlášky,- každá položka menu vedie na fungujúcu stránku, odkaz na registračný formulár v menu nie je,
- zoznam číta z databázy s JOIN a filter mení výpis aj URL,
- detail podľa id z URL funguje, pri neexistujúcom id vypíše hlášku,
- formulár v
add-ENTITY.phpzapíše do main entity aj pivot table adata.phpto ukáže, data.phpvypisuje každú table so SQL a má formulár pre každú lookup table,stats.phpmá JOIN, pivot table s názvami, GROUP BY a jeden record cezfetch,- všetko vo webovom priestore na sigma.tuke.sk (
ti/cv07/ati/projekt/) a v repository s aspoň 4 commitmi.
Before the round 2 defence you copy the submitted state: rsync -a --exclude .git cv07/ 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.
Explain (code walkthrough)
- What is in the DSN and what happens when the database name is wrong.
- What ERRMODE_EXCEPTION does and what the page looks like without it on an error.
- What FETCH_ASSOC does and how you then access a column value.
- When
queryis enough and when it must beprepare; show an example of each on a concrete line of your code. - What the placeholder
?is and what must match the number of question marks. - Why
preparestops SQL injection; what the database does with the text fromexecute. - Show in
content/detail.phpwhich line of the bad version is dangerous and why. - What
fetchAllreturns and whatfetchreturns; show where you have each. What each returns when the database found nothing. - What
lastInsertIdis for and what would happen without it when writing into the pivot table. - How many INSERTs are sent when writing a record with three checked pivot table items, and why.
- Why the checkbox has
name="x[]"and what is in$_POST['x']. - Why
prepareis before theforeachandexecuteinside it, not both inside. - How the select in the form got its
<option>elements and whyvalueis the id, not the name. - In
content/data.php: how PHP knows which form was submitted. - In
content/data.php: whatSELECT id ... WHERE name = ?before the INSERT does and what would happen without it. - In
content/data.php: whatarray_keys($rows[0])prints and why there isif ($rows)around the table. - What the JOIN listing in
ENTITY.phpreturns and whySELECT * FROM main_entityis not enough. - How the GET filter works: what is in the URL, what in
$_GET, which SELECT runs with an empty choice. - Why you print a value from the database through
htmlspecialcharswhen the application wrote it into the database. - What the message
foreign key constraint failsmeans for the form inadd-ENTITY.phpand how it can happen. - Why the page has
require 'db.php'in the page file inweb/and the content file only uses$pdo.
Modify (live coding)
- Add another column from the lookup table to the table in
stats.php(in the samplegrades.value). - Change the sorting of the list to another column and the opposite direction.
- Add a second choice to the filter (by another column or lookup table); a SELECT and a
?are enough. - Print the number of displayed records under the list (
count($rows)), if it is not there yet. - Make one optional input in the form in
add-ENTITY.phprequired and show the message. - Change the “most” listing from the largest to the smallest.
- Add a table to
stats.php: lookup table records that no main entity record uses (LEFT JOIN + IS NULL). - In
content/detail.phpswitch on the bad version, show the attack URL, then return it to prepare and show that the same URL returns nothing. - In
data.phpchange the order of the tables in the listing or addORDER BYto one SELECT. - Add a first option “choose” with an empty
valueto the select in the form inadd-ENTITY.phpand handle it in the validation, if it is not there yet.
Justify (design decisions)
- Why the connection is in one file with
requireand not in every file again. - Why the filter is sent through GET and the add forms through POST.
- Why you fill the select in the form from the database and not written in HTML.
- Why we do not use ways that paste values into SQL, although they exist.
- Why you chose this lookup table for the filter (what the user wants to find in
ENTITY.php). - Why the lookup table forms are in
data.phpnext to the listing and the main entity form has its own pageadd-ENTITY.php.
Definition of Done
db.phpconnects without a message,- every menu item leads to a working page, the link to the registration form is not in the menu,
- the list reads from the database with a JOIN and the filter changes the listing and the URL,
- the detail by id from the URL works and prints a message for a non-existent id,
- the form in
add-ENTITY.phpwrites into the main entity and the pivot table anddata.phpshows it, data.phplists every table with the SQL and has a form for every lookup table,stats.phphas a JOIN, the pivot table with names, GROUP BY and one record throughfetch,- everything is in your web space on sigma.tuke.sk (
ti/cv07/andti/projekt/) and in the repository with at least 4 commits.