Competency 10:
Web Development with HTML, CSS & PHP
Complete teaching guide — every sub-topic covered with theory, code examples, and exam focus notes.
10.1.1 – World Wide Web (WWW)
The World Wide Web (WWW) is a system of interlinked hypertext documents and multimedia content that is accessed via the Internet using a web browser. It was invented by Tim Berners-Lee in 1989 at CERN, Switzerland.
| Term | Meaning |
|---|---|
| WWW | System of web pages linked together using hyperlinks and URLs |
| HTTP | HyperText Transfer Protocol — the language used to transfer web pages |
| HTTPS | Secure version of HTTP using SSL/TLS encryption |
| URL | Uniform Resource Locator — address of a web resource (e.g. https://www.google.com) |
| Hyperlink | Clickable text or image that connects to another web page or resource |
| Web Browser | Software used to access the WWW (e.g. Chrome, Firefox, Edge) |
| Web Server | A computer that hosts and serves web pages over the Internet |
Necessity (Why we need the WWW):
- Share information globally at very low cost
- E-commerce (online shopping, banking)
- E-learning and online education
- Communication (email, social media, video calls)
- Entertainment (streaming, games)
- Government and public services
10.1.2 – Types of Web Sites
Websites can be broadly classified as Static or Dynamic.
| Type | Description | Technology | Example |
|---|---|---|---|
| Static | Content is fixed; same page shown to every user | HTML, CSS | Personal portfolio, brochure site |
| Dynamic | Content changes based on user, time, or data | PHP, Python + Database | Facebook, online shopping cart |
10.1.3 – Static Web Sites
A static website consists of fixed-content web pages stored as HTML files on the server. Every visitor sees exactly the same content.
Characteristics:
- Written in HTML and CSS only
- No database connection required
- Fast to load (no server-side processing)
- Difficult to update (must edit HTML directly)
- Suitable for small informational sites
10.1.4 – Dynamic Web Sites
A dynamic website generates content on the fly. The server processes requests and creates HTML pages by retrieving data from a database.
Characteristics:
- Content changes per user, session, or time
- Uses server-side languages (PHP, Python, Node.js)
- Requires a database (MySQL, PostgreSQL)
- Easy to update content via admin panel
- Examples: Facebook, Amazon, online banking
10.1.5 – Client-Side Scripting
Client-side scripting runs inside the user's web browser (the client). The script is downloaded to the browser and executed there.
- Language: JavaScript, HTML, CSS
- No server required after the page loads
- Used for: form validation, animations, interactive menus
- The source code is visible to the user
10.1.6 – Server-Side Scripting
Server-side scripting runs on the web server before the page is sent to the browser.
- Languages: PHP, Python (Django/Flask), ASP.NET, Node.js
- Processes data, accesses databases, generates HTML dynamically
- Source code is hidden from the user
- Used for: login systems, online shopping carts, content management
| Client-Side | Server-Side | |
|---|---|---|
| Where it runs | Browser (user's computer) | Web server |
| Language | JavaScript, HTML, CSS | PHP, Python, ASP.NET |
| Database access | No (directly) | Yes |
| Source visible? | Yes | No |
| Speed | Fast (no network needed) | Depends on server/network |
10.1.1 – World Wide Web (WWW) යනු කුමක්ද?
World Wide Web (WWW) යනු Internet හරහා web browser භාවිතයෙන් ප්රවේශ වන, hypertext documents සහ multimedia content ඒකාබද්ධ කළ ක්රමවේදයකි. එය Tim Berners-Lee විසින් 1989 දී Switzerland හි CERN ආයතනයේදී නිර්මාණය කරන ලදී.
| Term | අර්ථය |
|---|---|
| WWW | Hyperlinks සහ URLs භාවිතයෙන් ඒකාබද්ධ web pages ක්රමවේදය |
| HTTP | HyperText Transfer Protocol — web pages හුවමාරු කිරීමේ භාෂාව |
| HTTPS | SSL/TLS encryption භාවිතා කළ HTTP හි ආරක්ෂිත අනුවාදය |
| URL | Uniform Resource Locator — web resource හි ලිපිනය (උදා: https://www.google.com) |
| Hyperlink | වෙනත් web page හෝ resource වෙත සම්බන්ධ වන click කළ හැකි text හෝ image |
| Web Browser | WWW ප්රවේශ කිරීමට භාවිතා කරන software (උදා: Chrome, Firefox, Edge) |
| Web Server | Internet හරහා web pages host කර serve කරන computer |
WWW හි අවශ්යතාව (ඇයි WWW අවශ්ය?):
- ඉතා අඩු වියදමින් ලොව පුරා තොරතුරු බෙදාගැනීම
- E-commerce (online ගෙනීම, banking)
- E-learning සහ online අධ්යාපනය
- සන්නිවේදනය (email, social media, video calls)
- විනෝදාංශ (streaming, games)
- රජය සහ රාජ්ය සේවා
10.1.2 – Website වර්ග
Websites ප්රධාන ලෙස Static හෝ Dynamic ලෙස වර්ග කළ හැකිය.
| වර්ගය | විස්තරය | Technology | උදාහරණ |
|---|---|---|---|
| Static | Content ස්ථිරයි; සෑම user කෙනෙකුටම එකම page පෙනේ | HTML, CSS | පුද්ගලික portfolio, brochure site |
| Dynamic | User, වේලාව හෝ data අනුව content වෙනස් වේ | PHP, Python + Database | Facebook, online shopping cart |
10.1.3 – Static Web Sites
Static website යනු server හි HTML files ලෙස ගබඩා කළ, content නොවෙනස්ව ඇති web pages සමූහයකි. සෑම visitor කෙනෙකුටම එකම content පෙනේ.
ලක්ෂණ:
- HTML සහ CSS පමණක් භාවිතා කෙරේ
- Database සම්බන්ධතාවක් අවශ්ය නොවේ
- Server-side processing නොමැති නිසා ඉක්මනින් load වේ
- Update කිරීමට HTML file සෘජුව සංස්කරණය කළ යුතුය (අපහසු)
- කුඩා informational sites සඳහා සුදුසුය
10.1.4 – Dynamic Web Sites
Dynamic website content ගතිකව (fly) generate කරයි. Server requests process කර database වෙතින් data ලබා HTML pages නිර්මාණය කරයි.
ලක්ෂණ:
- User, session හෝ වේලාව අනුව content වෙනස් වේ
- Server-side languages (PHP, Python, Node.js) භාවිතා කෙරේ
- Database (MySQL, PostgreSQL) අවශ්ය වේ
- Admin panel හරහා content update කිරීම පහසුය
- උදාහරණ: Facebook, Amazon, online banking
10.1.5 – Client-Side Scripting
Client-side scripting user ගේ web browser (client) තුළ ක්රියාත්මක වේ. Script browser වෙත download වී එහිදීම execute වේ.
- භාෂා: JavaScript, HTML, CSS
- Page load වූ පසු server අවශ්ය නොවේ
- භාවිතය: form validation, animations, interactive menus
- Source code user ට දෘශ්ය (view source) වේ
10.1.6 – Server-Side Scripting
Server-side scripting page browser ට යැවීමට පෙර web server හිදී ක්රියාත්මක වේ.
- භාෂා: PHP, Python (Django/Flask), ASP.NET, Node.js
- Data process කර, databases access කර, HTML ගතිකව generate කරයි
- Source code user ට නොපෙනේ (සැඟවී ඇත)
- භාවිතය: login systems, online shopping carts, content management
| Client-Side | Server-Side | |
|---|---|---|
| ක්රියාත්මක වන තැන | Browser (user ගේ computer) | Web server |
| භාෂාව | JavaScript, HTML, CSS | PHP, Python, ASP.NET |
| Database access | නෑ (සෘජුව) | ඔව් |
| Source code දෘශ්යද? | ඔව් | නෑ |
| වේගය | ඉක්මන් (network අවශ්ය නෑ) | Server/network මත රඳා පවතී |
10.2.1 – Key Objective of a Web Site
Before building a website, you must understand the purpose and audience. Key questions to answer:
- Who is the target audience?
- What is the main goal? (sell products, share info, entertain?)
- What content is needed?
- How will users navigate the site?
- What devices will they use? (mobile, tablet, desktop)
- What are the performance requirements?
10.2.2 – Contents that has to be displayed
Content planning involves identifying:
- Text — headings, paragraphs, descriptions
- Images — photos, icons, logos
- Audio/Video — multimedia files
- Links — navigation between pages
- Forms — for user input (contact, registration)
- Tables — for structured data
10.2.3 – Connecting all Website Pages to a Menu on the Home Page
A website's navigation menu connects all pages. The home page (index.html) typically contains the main navigation with links (anchor tags) to all other pages.
<nav> <ul> <li><a href="index.html">Home</a></li> <li><a href="about.html">About Us</a></li> <li><a href="services.html">Services</a></li> <li><a href="contact.html">Contact</a></li> </ul> </nav>
10.2.1 – Website හි ප්රධාන අරමුණ
Website නිර්මාණය කිරීමට පෙර, අරමුණ සහ ඉලක්ක කණ්ඩායම (audience) තේරුම් ගත යුතුය. පිළිතුරු දිය යුතු ප්රශ්න:
- ඉලක්ක audience කවුද?
- ප්රධාන අරමුණ කුමක්ද? (products විකිණීම, information බෙදීම, විනෝද කිරීම?)
- කුමන content අවශ්යද?
- Users site navigate කරන්නේ කෙසේද?
- ඔවුන් භාවිතා කරන devices මොනවාද? (mobile, tablet, desktop)
- Performance requirements මොනවාද?
10.2.2 – දර්ශනය කළ යුතු Content
Content සැලසුම් කිරීමේදී හඳුනාගත යුතු දේ:
- Text — headings, paragraphs, descriptions
- Images — photos, icons, logos
- Audio/Video — multimedia files
- Links — pages අතර navigation
- Forms — user input සඳහා (contact, registration)
- Tables — ව්යූහගත data සඳහා
10.2.3 – Home Page Menu හරහා සියලු Pages සම්බන්ධ කිරීම
Website හි navigation menu සියලු pages සම්බන්ධ කරයි. Home page (index.html) සාමාන්යයෙන් anchor tags භාවිතා කළ main navigation ඇතුළත් කරයි.
<nav> <ul> <li><a href="index.html">Home</a></li> <li><a href="about.html">About Us</a></li> <li><a href="services.html">Services</a></li> <li><a href="contact.html">Contact</a></li> </ul> </nav>
10.3.1 – What is HTML?
HTML stands for HyperText Markup Language. It is the standard language used to create web pages. HTML describes the structure of a web page using tags.
- It is NOT a programming language — it is a markup language
- Current version: HTML5
- HTML files have the extension
.htmlor.htm - Created by Tim Berners-Lee
10.3.2 – Features of HTML Tag
- Tags are enclosed in angle brackets:
<tagname> - Most tags come in pairs: opening tag
<p>and closing tag</p> - Some tags are self-closing (void elements):
<br>,<img>,<hr> - Tags are case-insensitive (but lowercase is recommended)
- Tags can be nested (one inside another)
<!-- Opening tag + content + closing tag --> <p>This is a paragraph.</p> <!-- Self-closing tag (void element) --> <br> <!-- Line break --> <hr> <!-- Horizontal rule --> <img src="image.jpg"> <!-- Image -->
10.3.3 – Tag Attributes
Attributes provide additional information about HTML elements. They are placed inside the opening tag.
Syntax: <tagname attribute="value">
| Attribute | Used with | Purpose |
|---|---|---|
href | <a> | Specifies the link destination |
src | <img> | Specifies the image file path |
alt | <img> | Alternative text for image |
width, height | <img>, <table> | Sets dimensions |
style | Most tags | Inline CSS styling |
id | Most tags | Unique identifier |
class | Most tags | CSS class name |
name | Form elements | Name for form submission |
action | <form> | Where to send form data |
method | <form> | GET or POST |
10.3.3.1 – Quote Style for Attributes
Attribute values should be enclosed in double quotes "value". Single quotes 'value' are also valid.
10.3.4 – HTML Elements
An HTML element consists of: opening tag + content + closing tag.
<h1>Welcome to My Website</h1> │ │ │ Open Tag Content Close Tag
10.3.5 – Building Blocks of a Web Page
<!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <!-- Visible page content goes here --> <h1>Hello World!</h1> <p>This is my first web page.</p> </body> </html>
10.3.5.1 – Why we use the HTML Head Area
| Tag in <head> | Purpose |
|---|---|
<title> | Sets the browser tab title |
<meta charset="UTF-8"> | Character encoding (supports all languages) |
<meta name="description"> | Description for search engines |
<link rel="stylesheet"> | Links external CSS file |
<script> | Links JavaScript files |
10.3.5.2 – Why we use the Body Area
The <body> contains everything visible on the web page: headings, paragraphs, images, tables, forms, links, and all other content that appears in the browser window.
10.3.6 – Let's Create a Web Page
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>My First Web Page</title> </head> <body> <h1>Welcome to My Website</h1> <p>This is my first paragraph of text.</p> <p>HTML is easy to learn!</p> </body> </html>
10.3.7 – How to Save HTML Code
- Open a text editor (Notepad, VS Code, Sublime Text)
- Type or paste your HTML code
- Save the file with .html extension (e.g.
index.html) - Use Save As → All Files → filename.html in Notepad
- Encoding should be UTF-8
10.3.8 – How to Open a Web Page Through a Browser
- Open Windows Explorer and find the .html file
- Double-click the file — it opens in the default browser
- Or open the browser → File → Open File
- Or drag the .html file into the browser window
<!DOCTYPE html> declares the document type. Without it, the browser may render in "quirks mode".10.3.1 – HTML යනු කුමක්ද?
HTML = HyperText Markup Language. Web pages නිර්මාණය කිරීමට භාවිතා කරන සම්මත භාෂාවයි. HTML tags භාවිතයෙන් web page හි ව්යූහය (structure) විස්තර කරයි.
- Programming language නොවේ — markup language ය
- වත්මන් අනුවාදය: HTML5
- HTML files හි extension:
.htmlහෝ.htm - නිර්මාතෘ: Tim Berners-Lee
10.3.2 – HTML Tag හි ලක්ෂණ
- Tags angle brackets ඇතුළේ ලිවිය යුතුය:
<tagname> - බොහෝ tags ජෝඩු ලෙස ලිවිය යුතුය: opening tag
<p>සහ closing tag</p> - ඇතැම් tags self-closing (void elements):
<br>,<img>,<hr> - Tags case-insensitive (නමුත් lowercase නිර්දේශ කෙරේ)
- Tags nested (ඒකක ඇතුළේ ඒකක) ලෙස ලිවිය හැකිය
<!-- Opening tag + content + closing tag --> <p>මෙය paragraph එකකි.</p> <!-- Self-closing tag (void element) --> <br> <!-- Line break --> <hr> <!-- Horizontal rule --> <img src="image.jpg"> <!-- Image -->
10.3.3 – Tag Attributes
Attributes HTML elements පිළිබඳ අතිරේක තොරතුරු සපයයි. Opening tag ඇතුළේ ලිවිය යුතුය.
Syntax: <tagname attribute="value">
| Attribute | Tags | අරමුණ |
|---|---|---|
href | <a> | Link destination නිශ්චිත කරයි |
src | <img> | Image file path නිශ්චිත කරයි |
alt | <img> | Image සඳහා විකල්ප text |
width, height | <img>, <table> | Dimensions set කරයි |
style | බොහෝ tags | Inline CSS styling |
id | බොහෝ tags | අනන්ය හඳුනාගැනීමේ ලකුණ |
class | බොහෝ tags | CSS class නාමය |
name | Form elements | Form submission සඳහා නාමය |
action | <form> | Form data යවන ස්ථානය |
method | <form> | GET හෝ POST |
10.3.3.1 – Attributes සඳහා Quote ශෛලිය
Attribute values double quotes "value" ඇතුළේ ලිවිය යුතුය. Single quotes 'value' ද ස්වීකාර්ය ය.
10.3.4 – HTML Elements
HTML element = opening tag + content + closing tag.
<h1>Welcome to My Website</h1> │ │ │ Open Tag Content Close Tag
10.3.5 – Web Page හි ගොඩනැගීමේ ආකෘතිය
<!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <!-- දෘශ්ය page content මෙහි ලිවිය යුතුය --> <h1>Hello World!</h1> <p>This is my first web page.</p> </body> </html>
10.3.5.1 – HTML Head Area භාවිතා කරන්නේ ඇයි?
| <head> ඇතුළේ Tag | අරමුණ |
|---|---|
<title> | Browser tab title set කරයි |
<meta charset="UTF-8"> | Character encoding (සිංහල ඇතුළු සියලු භාෂා support) |
<meta name="description"> | Search engines සඳහා description |
<link rel="stylesheet"> | External CSS file සම්බන්ධ කරයි |
<script> | JavaScript files සම්බන්ධ කරයි |
10.3.5.2 – Body Area භාවිතා කරන්නේ ඇයි?
<body> ඇතුළේ web page හි දෘශ්ය සියල්ල ලිවිය යුතුය: headings, paragraphs, images, tables, forms, links සහ browser window හි දිස්වන සෑම content එකක්ම.
10.3.6 – Web Page නිර්මාණය කරමු
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>My First Web Page</title> </head> <body> <h1>Welcome to My Website</h1> <p>This is my first paragraph of text.</p> <p>HTML is easy to learn!</p> </body> </html>
10.3.7 – HTML Code Save කරන ආකාරය
- Text editor (Notepad, VS Code, Sublime Text) විවෘත කරන්න
- HTML code type කරන්න හෝ paste කරන්න
- .html extension සමඟ file save කරන්න (උදා:
index.html) - Notepad හි: Save As → All Files → filename.html ලෙස save කරන්න
- Encoding: UTF-8 ලෙස select කරන්න
10.3.8 – Browser හරහා Web Page විවෘත කිරීම
- Windows Explorer විවෘත කර .html file සොයන්න
- File Double-click කරන්න — default browser හි ස්වයංක්රීයව විවෘත වේ
- Browser විවෘත කර → File → Open File ලෙස ද කළ හැකිය
- .html file browser window ඇතුළට drag කළ හැකිය
<!DOCTYPE html> document type ප්රකාශ කරයි. නොමැති නම් browser "quirks mode" හි render කිරීමට ඉඩ ඇත — මෙය විභාගයේ ලියන්නට ඉඩ ඇත.10.4.1 – <p> — Paragraph
The <p> tag defines a paragraph. Browsers automatically add space before and after paragraphs.
<p>This is a paragraph.</p> <p>This is another paragraph.</p>
10.4.2 – <br> — Line Break
The <br> tag inserts a single line break. It is a self-closing (void) tag — no closing tag needed.
<p>Line one.<br>Line two.<br>Line three.</p>
10.4.3 – <H1> to <H6> — Headings
HTML has 6 levels of headings. <h1> is the largest and most important; <h6> is the smallest.
<h1>Heading 1 — Main Title</h1> <h2>Heading 2 — Section Title</h2> <h3>Heading 3 — Sub-section</h3> <h4>Heading 4</h4> <h5>Heading 5</h5> <h6>Heading 6 — Smallest</h6>
10.4.4 – <font size> — Font Size
The <font> tag (older HTML) changes font size. Values range from 1 to 7 (default is 3).
<font size="5">Large text</font> <font size="2">Small text</font> <!-- Modern equivalent with CSS: --> <p style="font-size: 24px;">Large text</p>
font-size property instead.10.4.5 – <b> — Bold
<b>This text is bold.</b> <!-- Also: <strong> for semantically important bold text --> <strong>This is important bold text.</strong>
10.4.6 – <i> — Italic
<i>This text is italic.</i> <!-- Also: <em> for semantically emphasised text --> <em>This is emphasised text.</em>
10.4.7 – <u> — Underline
<u>This text is underlined.</u>
10.4.8 – <strong> — Strong Importance
<strong> marks text as very important. It is visually bold AND semantically important (used by screen readers and search engines).
<p>Do <strong>NOT</strong> press this button!</p>
10.4.9 – Alignment — align Attribute
<p align="left">Left aligned</p> <p align="center">Center aligned</p> <p align="right">Right aligned</p> <p align="justify">Justified text</p> <!-- Modern CSS approach --> <p style="text-align: center;">Centered</p>
10.4.10 – <sub> — Subscript
<p>H<sub>2</sub>O (Water)</p> <p>CO<sub>2</sub> (Carbon Dioxide)</p>
10.4.11 – <sup> — Superscript
<p>E = mc<sup>2</sup></p> <p>5<sup>th</sup> August</p>
10.4.12 – <font face> — Font Family
<font face="Arial">Arial font</font> <font face="Times New Roman">Times New Roman</font> <!-- Modern CSS approach: --> <p style="font-family: Arial, sans-serif;">Arial text</p>
10.4.13 – How to use Colours in a Web Page
Colours in HTML can be specified in three ways:
| Method | Example | Description |
|---|---|---|
| Named colours | red, blue, green | Predefined colour names (140 standard names) |
| Hex code | #FF0000 | Hexadecimal RGB (most common) |
| RGB value | rgb(255, 0, 0) | Red, Green, Blue values (0–255) |
<font color="red">Red text</font> <font color="#0000FF">Blue text</font> <!-- CSS approach (preferred): --> <p style="color: #FF5733;">Orange text</p>
10.4.13.1 – Applying Background Colours
<!-- Entire page background --> <body bgcolor="#FFFF00"> <!-- Yellow background --> <!-- Background for a section (CSS): --> <p style="background-color: lightblue;">Blue background</p>
10.4.1 – <p> — Paragraph
<p> tag paragraph නිර්වචනය කරයි. Browser ස්වයංක්රීයව paragraphs ඉදිරිපිට සහ පසුපිට space add කරයි.
<p>මෙය paragraph එකකි.</p> <p>මෙය තවත් paragraph එකකි.</p>
10.4.2 – <br> — Line Break
<br> tag single line break insert කරයි. Self-closing (void) tag — closing tag අවශ්ය නොවේ.
<p>Line one.<br>Line two.<br>Line three.</p>
10.4.3 – <H1> සිට <H6> — Headings
HTML හි headings 6ක් ඇත. <h1> ලොකුම සහ වැදගත්ම; <h6> කුඩාම ය.
<h1>Heading 1 — ප්රධාන Title</h1> <h2>Heading 2 — Section Title</h2> <h3>Heading 3 — Sub-section</h3> <h4>Heading 4</h4> <h5>Heading 5</h5> <h6>Heading 6 — කුඩාම</h6>
10.4.4 – <font size> — Font Size
පැරණි HTML හි <font> tag font size වෙනස් කරයි. Values 1 සිට 7 (default: 3).
<font size="5">Large text</font> <font size="2">Small text</font> <!-- CSS හරහා නවීන ක්රමය: --> <p style="font-size: 24px;">Large text</p>
font-size property භාවිතා කරන්න.10.4.5 – <b> — Bold
<b>මෙය bold text.</b> <!-- සේමෝ: <strong> — semantically වැදගත් bold text --> <strong>මෙය වැදගත් bold text.</strong>
10.4.6 – <i> — Italic
<i>මෙය italic text.</i> <!-- සේමෝ: <em> — semantically emphasized text --> <em>මෙය emphasized text.</em>
10.4.7 – <u> — Underline
<u>මෙය underlined text.</u>
10.4.8 – <strong> — Strong Importance
<strong> text ඉතා වැදගත් ලෙස සලකුණු කරයි. දෘශ්යමාන bold AND semantically වැදගත් (screen readers සහ search engines ද හඳුනාගනී).
<p>DO <strong>NOT</strong> press this button!</p>
10.4.9 – Alignment — align Attribute
<p align="left">වම් align</p> <p align="center">මධ්ය align</p> <p align="right">දකුණු align</p> <p align="justify">Justified text</p> <!-- නවීන CSS ක්රමය --> <p style="text-align: center;">Centered</p>
10.4.10 – <sub> — Subscript
<p>H<sub>2</sub>O (Water)</p> <p>CO<sub>2</sub> (Carbon Dioxide)</p>
10.4.11 – <sup> — Superscript
<p>E = mc<sup>2</sup></p> <p>5<sup>th</sup> August</p>
10.4.12 – <font face> — Font Family
<font face="Arial">Arial font</font> <font face="Times New Roman">Times New Roman</font> <!-- නවීන CSS ක්රමය: --> <p style="font-family: Arial, sans-serif;">Arial text</p>
10.4.13 – Web Page හි වර්ණ භාවිතය
HTML හි වර්ණ ක්රම තුනකින් සඳහන් කළ හැකිය:
| ක්රමය | උදාහරණ | විස්තරය |
|---|---|---|
| Named colours | red, blue, green | පූර්ව-නිර්වචිත වර්ණ නාම (සම්මත නාම 140) |
| Hex code | #FF0000 | Hexadecimal RGB (වඩාත් සාමාන්ය) |
| RGB value | rgb(255, 0, 0) | Red, Green, Blue values (0–255) |
<font color="red">Red text</font> <font color="#0000FF">Blue text</font> <!-- CSS ක්රමය (නිර්දේශිත): --> <p style="color: #FF5733;">Orange text</p>
10.4.13.1 – Background Colours යෙදීම
<!-- සම්පූර්ණ page background --> <body bgcolor="#FFFF00"> <!-- Yellow background --> <!-- Section background (CSS): --> <p style="background-color: lightblue;">Blue background</p>
10.5.1–10.5.3 – Content, Home Page & Linked Pages
Websites consist of multiple linked pages. The anchor tag <a> creates hyperlinks.
<!-- Link to another page on the same site --> <a href="about.html">About Us</a> <!-- Link to external website --> <a href="https://www.google.com">Go to Google</a> <!-- Email link --> <a href="mailto:info@example.com">Email Us</a> <!-- Link to a section on same page (anchor) --> <a href="#section2">Jump to Section 2</a> <h2 id="section2">Section 2</h2>
10.5.4 – Opening a Web Page in a New Window
Use target="_blank" to open the link in a new browser tab/window.
<a href="https://www.example.com" target="_blank"> Open in New Tab </a> <!-- target values: --> <!-- _blank = new tab/window --> <!-- _self = same tab (default) --> <!-- _parent = parent frame --> <!-- _top = top-level window -->
10.5.5 – How to Use Lists in HTML
10.5.5.1 – Ordered Lists
An ordered list uses numbers or letters. Tag: <ol>. Items use <li>.
<ol> <li>First item</li> <li>Second item</li> <li>Third item</li> </ol> <!-- type attribute: 1 (numbers), A (uppercase), a (lowercase), I (Roman), i --> <ol type="A"> <li>Item A</li> <li>Item B</li> </ol> <!-- start attribute: start numbering from --> <ol start="5"> <li>Fifth item</li> </ol>
10.5.5.2 – Unordered Lists
An unordered list uses bullet points. Tag: <ul>.
<ul> <li>Apples</li> <li>Bananas</li> <li>Oranges</li> </ul> <!-- type: disc (default), circle, square --> <ul type="square"> <li>Square bullets</li> </ul> <!-- Nested list --> <ul> <li>Fruits <ul> <li>Apple</li> <li>Mango</li> </ul> </li> </ul>
10.5.6 – HTML Images
The <img> tag inserts an image. It is a self-closing tag.
<img src="photo.jpg" alt="A beautiful photo" width="300" height="200"> <!-- Attributes: src = path/URL to image file (required) alt = alternative text (required for accessibility) width = width in pixels height = height in pixels title = tooltip text on hover --> <!-- Image as a link --> <a href="page.html"> <img src="logo.png" alt="Logo"> </a>
10.5.6.1 – Image Path
| Path Type | Example | Meaning |
|---|---|---|
| Same folder | src="image.jpg" | Image is in the same folder as HTML file |
| Subfolder | src="images/photo.jpg" | Image is inside an "images" subfolder |
| Parent folder | src="../image.jpg" | Image is one folder up |
| Absolute URL | src="https://example.com/img.jpg" | Image from the internet |
10.5.7 – HTML Tables
| Tag | Meaning |
|---|---|
<table> | Defines the table |
<tr> | Table Row |
<th> | Table Header cell (bold + centered by default) |
<td> | Table Data cell |
<caption> | Table caption/title |
<table border="1" width="400" cellpadding="5" cellspacing="2"> <caption>Student Marks</caption> <tr> <th>Name</th> <th>Subject</th> <th>Marks</th> </tr> <tr> <td>Kamal</td> <td>ICT</td> <td>90</td> </tr> <tr> <td>Nimal</td> <td>ICT</td> <td>85</td> </tr> </table>
10.5.7.1 – Table Border
border="1" adds a 1-pixel border. border="0" removes the border.
10.5.7.2 – Cell Padding
cellpadding="10" — space inside each cell between the content and the cell wall.
10.5.7.3 – Cell Spacing
cellspacing="5" — space between adjacent cells.
10.5.7.4 – Align Attribute
<table align="center"> <!-- center table on page --> <td align="right">Right aligned cell</td> <td valign="top">Top vertical align</td>
10.5.7.5 – Set an Image as Table Background
<table background="bg.jpg" width="100%"> <tr><td>Content on image background</td></tr> </table>
10.5.7.6 – Setting the Total Width of the Table
<table width="600"> <!-- Fixed pixel width --> <table width="80%"> <!-- Percentage of page width -->
10.5.7.7 – Rowspan and Colspan
These attributes merge cells across rows or columns.
<table border="1"> <tr> <!-- colspan: span across 2 columns --> <th colspan="2">Name & Age</th> <th>Subject</th> </tr> <tr> <!-- rowspan: span across 2 rows --> <td rowspan="2">Kamal</td> <td>20</td> <td>ICT</td> </tr> <tr> <td>21</td> <td>Maths</td> </tr> </table>
10.5.8 – Animation using <marquee>
The <marquee> tag creates scrolling/moving text.
<!-- Basic scrolling text --> <marquee>This text scrolls across the screen!</marquee> <!-- With attributes --> <marquee behavior="scroll" direction="right" scrollamount="5" bgcolor="yellow"> Scrolling Right </marquee> <!-- behavior: scroll | slide | alternate --> <!-- direction: left (default) | right | up | down --> <!-- scrollamount: speed (pixels per step) --> <!-- scrolldelay: delay between each step (ms) --> <!-- loop: number of times (-1 = infinite) -->
10.5.9 – Multimedia Objects
10.5.9.1 – How to add Audio and Video
<!-- HTML5 Audio --> <audio controls> <source src="music.mp3" type="audio/mpeg"> <source src="music.ogg" type="audio/ogg"> Your browser does not support audio. </audio> <!-- Attributes: controls, autoplay, loop, muted -->
<!-- HTML5 Video --> <video width="640" height="360" controls> <source src="movie.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> Your browser does not support video. </video> <!-- Attributes: controls, autoplay, loop, muted, poster --> <!-- poster = image shown before video plays -->
| Attribute | Effect |
|---|---|
controls | Shows play/pause/volume controls |
autoplay | Starts playing automatically |
loop | Repeats the media continuously |
muted | Starts with no sound |
poster | Image shown before video loads (video only) |
10.5.10 – <div> — Division / Section
The <div> tag defines a block-level container (division) for grouping HTML elements. It has no visual effect on its own but is used with CSS for layout.
<div id="header" style="background-color: navy; color: white;"> <h1>Website Header</h1> </div> <div id="content"> <p>Main content area</p> </div> <div id="footer"> <p>Footer content</p> </div>
10.5.1–10.5.3 – Content, Home Page සහ Linked Pages
Websites linked pages කිහිපයකින් සමන්විත වේ. Anchor tag <a> hyperlinks නිර්මාණය කරයි.
<!-- එකම site හි වෙනත් page වෙත link --> <a href="about.html">About Us</a> <!-- External website වෙත link --> <a href="https://www.google.com">Go to Google</a> <!-- Email link --> <a href="mailto:info@example.com">Email Us</a> <!-- එකම page හි section වෙත link (anchor) --> <a href="#section2">Jump to Section 2</a> <h2 id="section2">Section 2</h2>
10.5.4 – නව Window/Tab හි Web Page විවෘත කිරීම
නව browser tab/window හි link විවෘත කිරීමට target="_blank" භාවිතා කරන්න.
<a href="https://www.example.com" target="_blank"> නව Tab හි විවෘත කරන්න </a> <!-- target values: --> <!-- _blank = නව tab/window --> <!-- _self = එකම tab (default) --> <!-- _parent = parent frame --> <!-- _top = top-level window -->
10.5.5 – HTML හි Lists භාවිතය
10.5.5.1 – Ordered Lists
Ordered list ක්රමාංක හෝ අකුරු භාවිතා කරයි. Tag: <ol>. Items: <li>.
<ol> <li>පළමු item</li> <li>දෙවන item</li> <li>තෙවන item</li> </ol> <!-- type attribute: 1 (ලකුණු), A (uppercase), a (lowercase), I (Roman), i --> <ol type="A"> <li>Item A</li> <li>Item B</li> </ol> <!-- start attribute: ආරම්භ ලකුණ --> <ol start="5"> <li>Fifth item</li> </ol>
10.5.5.2 – Unordered Lists
Unordered list bullet points භාවිතා කරයි. Tag: <ul>.
<ul> <li>Apples</li> <li>Bananas</li> <li>Oranges</li> </ul> <!-- type: disc (default), circle, square --> <ul type="square"> <li>Square bullets</li> </ul> <!-- Nested list (ඇතුළත list) --> <ul> <li>Fruits <ul> <li>Apple</li> <li>Mango</li> </ul> </li> </ul>
10.5.6 – HTML Images
<img> tag image insert කරයි. Self-closing tag ය.
<img src="photo.jpg" alt="A beautiful photo" width="300" height="200"> <!-- Attributes: src = image file path/URL (අවශ්ය) alt = alternative text (accessibility සඳහා අවශ්ය) width = pixels ලෙස width height = pixels ලෙස height title = hover කළ විට tooltip text --> <!-- Image link ලෙස --> <a href="page.html"> <img src="logo.png" alt="Logo"> </a>
10.5.6.1 – Image Path
| Path වර්ගය | උදාහරණ | අර්ථය |
|---|---|---|
| එකම folder | src="image.jpg" | Image, HTML file සමඟ එකම folder හි ඇත |
| Subfolder | src="images/photo.jpg" | Image "images" subfolder ඇතුළේ ඇත |
| Parent folder | src="../image.jpg" | Image ඉහළ folder හි ඇත |
| Absolute URL | src="https://example.com/img.jpg" | Internet හි image |
10.5.7 – HTML Tables
| Tag | අර්ථය |
|---|---|
<table> | Table නිර්වචනය කරයි |
<tr> | Table Row (පේළිය) |
<th> | Table Header cell (default: bold + centered) |
<td> | Table Data cell (කොටුව) |
<caption> | Table caption/title |
<table border="1" width="400" cellpadding="5" cellspacing="2"> <caption>ශිෂ්ය ලකුණු</caption> <tr> <th>නම</th> <th>විෂය</th> <th>ලකුණු</th> </tr> <tr> <td>Kamal</td> <td>ICT</td> <td>90</td> </tr> <tr> <td>Nimal</td> <td>ICT</td> <td>85</td> </tr> </table>
10.5.7.1 – Table Border
border="1" pixel 1ක border add කරයි. border="0" border ඉවත් කරයි.
10.5.7.2 – Cell Padding
cellpadding="10" — content සහ cell wall අතර ඇතුළත space.
10.5.7.3 – Cell Spacing
cellspacing="5" — suddharth cells අතර space.
10.5.7.4 – Align Attribute
<table align="center"> <!-- page හි table center --> <td align="right">දකුණු align cell</td> <td valign="top">ඉහළ vertical align</td>
10.5.7.5 – Table Background ලෙස Image Set කිරීම
<table background="bg.jpg" width="100%"> <tr><td>Image background සහිත Content</td></tr> </table>
10.5.7.6 – Table හි සම්පූර්ණ Width Set කිරීම
<table width="600"> <!-- Fixed pixel width --> <table width="80%"> <!-- Page width හි percentage -->
10.5.7.7 – Rowspan සහ Colspan
මෙම attributes rows හෝ columns හරහා cells merge (ඒකාබද්ධ) කරයි.
<table border="1"> <tr> <!-- colspan: columns 2ක් හරහා extend --> <th colspan="2">නම & වයස</th> <th>විෂය</th> </tr> <tr> <!-- rowspan: rows 2ක් හරහා extend --> <td rowspan="2">Kamal</td> <td>20</td> <td>ICT</td> </tr> <tr> <td>21</td> <td>Maths</td> </tr> </table>
10.5.8 – <marquee> Animation
<marquee> tag scrolling/moving text නිර්මාණය කරයි.
<!-- Basic scrolling text --> <marquee>මෙම text screen හරහා scroll වේ!</marquee> <!-- Attributes සමඟ --> <marquee behavior="scroll" direction="right" scrollamount="5" bgcolor="yellow"> Scrolling Right </marquee> <!-- behavior: scroll | slide | alternate --> <!-- direction: left (default) | right | up | down --> <!-- scrollamount: වේගය (pixels per step) --> <!-- scrolldelay: delay (ms) --> <!-- loop: හැරෙන ගණන (-1 = infinite) -->
10.5.9 – Multimedia Objects
10.5.9.1 – Audio සහ Video add කිරීම
<!-- HTML5 Audio --> <audio controls> <source src="music.mp3" type="audio/mpeg"> <source src="music.ogg" type="audio/ogg"> ඔබේ browser audio support නොකරයි. </audio> <!-- Attributes: controls, autoplay, loop, muted -->
<!-- HTML5 Video --> <video width="640" height="360" controls> <source src="movie.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> ඔබේ browser video support නොකරයි. </video> <!-- Attributes: controls, autoplay, loop, muted, poster --> <!-- poster = video play වීමට පෙර දිස්වන image -->
| Attribute | ක්රියාව |
|---|---|
controls | Play/pause/volume controls පෙන්වයි |
autoplay | ස්වයංක්රීයව play ආරම්භ කරයි |
loop | Media නිරන්තරව repeat කරයි |
muted | Sound නොමැතිව ආරම්භ කරයි |
poster | Video load වීමට පෙර image (video only) |
10.5.10 – <div> — Division / Section
<div> tag HTML elements group කිරීමේ block-level container (division) නිර්වචනය කරයි. තනිව visual effect නොමැත — CSS layout සඳහා භාවිතා කෙරේ.
<div id="header" style="background-color: navy; color: white;"> <h1>Website Header</h1> </div> <div id="content"> <p>Main content area</p> </div> <div id="footer"> <p>Footer content</p> </div>
HTML forms collect input from the user and send it to a server for processing.
10.6.1.1 – <form> Tag
<form action="process.php" method="post"> <!-- Form elements go here --> </form> <!-- action = URL where form data is sent --> <!-- method = get (visible in URL) or post (hidden, more secure) -->
| Attribute | Value | Description |
|---|---|---|
action | URL | Script that processes the form |
method | get / post | How data is sent to server |
enctype | multipart/form-data | Required for file uploads |
10.6.1.2 – Text Input Field
<label for="fname">First Name:</label> <input type="text" id="fname" name="firstname" placeholder="Enter your name" maxlength="50" size="30">
10.6.1.3 – Password Input
<label for="pwd">Password:</label> <input type="password" id="pwd" name="password"> <!-- Characters are hidden (shown as ****) -->
10.6.1.4 – Text Area
<label for="msg">Message:</label><br> <textarea id="msg" name="message" rows="5" cols="40" placeholder="Type your message here..."> </textarea>
10.6.1.5 – Selection Boxes (Dropdown)
<label for="city">City:</label> <select id="city" name="city"> <option value="colombo">Colombo</option> <option value="kandy" selected>Kandy</option> <option value="galle">Galle</option> </select> <!-- selected = pre-selected option --> <!-- multiple attribute = allows multiple selections -->
10.6.1.6 – Radio Buttons
<p>Gender:</p> <input type="radio" id="male" name="gender" value="male"> <label for="male">Male</label> <input type="radio" id="female" name="gender" value="female"> <label for="female">Female</label> <!-- Radio buttons with the SAME name form a group. Only ONE can be selected at a time. -->
10.6.1.7 – Check Boxes
<p>Hobbies:</p> <input type="checkbox" id="reading" name="hobby" value="reading"> <label for="reading">Reading</label> <input type="checkbox" id="sports" name="hobby" value="sports" checked> <label for="sports">Sports</label> <!-- Multiple checkboxes can be selected at the same time --> <!-- checked = pre-selected -->
10.6.1.8 – Submit Button
<input type="submit" value="Submit Form"> <!-- Or using <button> tag: --> <button type="submit">Submit</button>
10.6.1.9 – Reset Button
<input type="reset" value="Clear Form"> <!-- Clears all form inputs back to default values -->
<form action="register.php" method="post"> <label>Name: <input type="text" name="name"></label><br> <label>Email: <input type="email" name="email"></label><br> <label>Password: <input type="password" name="pwd"></label><br> <p>Gender: <input type="radio" name="gender" value="M"> Male <input type="radio" name="gender" value="F"> Female </p> <label>City: <select name="city"> <option>Colombo</option> <option>Kandy</option> </select> </label><br> <label>Message: <br> <textarea name="msg" rows="4" cols="30"></textarea> </label><br> <input type="submit" value="Register"> <input type="reset" value="Clear"> </form>
HTML forms user ගෙන් input සගන්වා server වෙත processing සඳහා යවයි.
10.6.1.1 – <form> Tag
<form action="process.php" method="post"> <!-- Form elements මෙහි ඇතුළත් කරන්න --> </form> <!-- action = form data යවන URL --> <!-- method = get (URL හි දිස්වේ) හෝ post (සැඟවී, ආරක්ෂිත) -->
| Attribute | Value | විස්තරය |
|---|---|---|
action | URL | Form process කරන script |
method | get / post | Data server වෙත යවන ක්රමය |
enctype | multipart/form-data | File uploads සඳහා අවශ්ය |
10.6.1.2 – Text Input Field
<label for="fname">First Name:</label> <input type="text" id="fname" name="firstname" placeholder="ඔබේ නම ඇතුළු කරන්න" maxlength="50" size="30">
10.6.1.3 – Password Input
<label for="pwd">Password:</label> <input type="password" id="pwd" name="password"> <!-- Characters සැඟවී ඇත (****ලෙස පෙනේ) -->
10.6.1.4 – Text Area
<label for="msg">Message:</label><br> <textarea id="msg" name="message" rows="5" cols="40" placeholder="ඔබේ message type කරන්න..."> </textarea>
10.6.1.5 – Selection Boxes (Dropdown)
<label for="city">City:</label> <select id="city" name="city"> <option value="colombo">Colombo</option> <option value="kandy" selected>Kandy</option> <option value="galle">Galle</option> </select> <!-- selected = පූර්ව-තෝරාගත් option --> <!-- multiple attribute = multiple selection -->
10.6.1.6 – Radio Buttons
<p>ස්ත්රී/පුරුෂ භාවය:</p> <input type="radio" id="male" name="gender" value="male"> <label for="male">Male</label> <input type="radio" id="female" name="gender" value="female"> <label for="female">Female</label> <!-- එකම name ඇති radio buttons group කෙරේ. එකවිට එකක් පමණ select කළ හැකිය. -->
10.6.1.7 – Check Boxes
<p>Hobbies:</p> <input type="checkbox" id="reading" name="hobby" value="reading"> <label for="reading">Reading</label> <input type="checkbox" id="sports" name="hobby" value="sports" checked> <label for="sports">Sports</label> <!-- Checkboxes කිහිපයක් එකවිට select කළ හැකිය --> <!-- checked = පූර්ව-selected -->
10.6.1.8 – Submit Button
<input type="submit" value="Form Submit කරන්න"> <!-- හෝ <button> tag: --> <button type="submit">Submit</button>
10.6.1.9 – Reset Button
<input type="reset" value="Form Clear කරන්න"> <!-- Form inputs default values වෙත clear කරයි -->
<form action="register.php" method="post"> <label>Name: <input type="text" name="name"></label><br> <label>Email: <input type="email" name="email"></label><br> <label>Password: <input type="password" name="pwd"></label><br> <p>Gender: <input type="radio" name="gender" value="M"> Male <input type="radio" name="gender" value="F"> Female </p> <label>City: <select name="city"> <option>Colombo</option> <option>Kandy</option> </select> </label><br> <label>Message: <br> <textarea name="msg" rows="4" cols="30"></textarea> </label><br> <input type="submit" value="Register"> <input type="reset" value="Clear"> </form>
Websites are viewed using a web browser. Popular browsers include:
- Google Chrome — most widely used
- Mozilla Firefox
- Microsoft Edge
- Apple Safari
- Opera
10.7.1 – What are Search Engines?
A search engine is a software system that searches the web and returns a list of results based on keywords the user types. Examples:
| Search Engine | URL |
|---|---|
| www.google.com | |
| Bing | www.bing.com |
| Yahoo | www.yahoo.com |
| DuckDuckGo | www.duckduckgo.com |
How search engines work:
- Crawling — robots (spiders) browse the web and collect web pages
- Indexing — web pages are stored and organised in a database
- Ranking — when you search, results are ranked by relevance
- Displaying results — SERP (Search Engine Results Page) is shown
Websites බලනු ලබන්නේ web browser භාවිතයෙනි. ජනප්රිය browsers:
- Google Chrome — ලොව වැඩිම භාවිතා කරන browser
- Mozilla Firefox
- Microsoft Edge
- Apple Safari
- Opera
10.7.1 – Search Engines යනු කුමක්ද?
Search engine යනු user type කරන keywords ඉලකු ව web ශෝධනය කර ප්රතිඵල ලැයිස්තුවක් ලබා දෙන software ක්රමවේදයකි.
| Search Engine | URL |
|---|---|
| www.google.com | |
| Bing | www.bing.com |
| Yahoo | www.yahoo.com |
| DuckDuckGo | www.duckduckgo.com |
Search engines ක්රියා කරන ආකාරය:
- Crawling — robots (spiders) web browse කර pages collect කරයි
- Indexing — pages database හි ගබඩා කර සංවිධානය කරයි
- Ranking — search කළ විට relevance අනුව ප්රතිඵල rank කරයි
- Displaying results — SERP (Search Engine Results Page) දර්ශනය කරයි
CSS (Cascading Style Sheets) controls the appearance (presentation) of HTML elements — colours, fonts, layout, spacing, and more.
10.8.1 – Advantages of CSS
- Separates content (HTML) from presentation (CSS)
- One CSS file can style multiple pages — easier to maintain
- Reduces HTML code — pages load faster
- Enables consistent look across the entire website
- Supports responsive design for different screen sizes
- More control over layout than HTML attributes
10.9 – CSS Syntax
/* selector { property: value; } */ p { color: blue; font-size: 16px; text-align: center; } /* selector = which HTML element to style property = what to change (color, font-size, etc.) value = the new value Rules end with semicolons ; */
10.9.1 – CSS Styling Methods
10.9.1.1 – Inline CSS
Applied directly to a single HTML element using the style attribute.
<p style="color: red; font-size: 18px; font-weight: bold;"> This paragraph is red and bold. </p>
⊕ Quick and specific. ⊖ Hard to maintain; can't reuse styles.
10.9.1.2 – Internal CSS
CSS written inside a <style> tag in the <head> section of the HTML file.
<head> <style> body { background-color: #f0f0f0; font-family: Arial, sans-serif; } h1 { color: navy; text-align: center; } p { font-size: 16px; line-height: 1.6; } </style> </head>
⊕ Styles all elements on one page. ⊖ Can't share styles between pages.
10.9.1.3 – External CSS
CSS written in a separate .css file, linked to the HTML file.
<head> <link rel="stylesheet" href="style.css"> </head>
body { background-color: white; font-family: Verdana, sans-serif; margin: 0; padding: 0; } h1 { color: #333333; text-align: center; } p { font-size: 15px; color: #555555; }
⊕ One file styles the entire website. ⊕ Easiest to maintain. Best practice!
| Method | Where Written | Priority | Best For |
|---|---|---|---|
| Inline | Inside HTML tag | Highest | One-off styles |
| Internal | <style> in <head> | Medium | Single page |
| External | Separate .css file | Lowest | Multiple pages (BEST) |
CSS (Cascading Style Sheets) HTML elements හි පෙනුම (presentation) — වර්ණ, fonts, layout, spacing ආදිය — control කරයි.
10.8.1 – CSS හි වාසි
- Content (HTML) සහ presentation (CSS) වෙන් කරයි
- CSS file එකක් pages කිහිපයකට style කළ හැකිය — maintain කිරීම පහසුය
- HTML code අඩු කරයි — pages ඉක්මනින් load වේ
- සම්පූර්ණ website හරහා consistent පෙනුමක් ලබා දේ
- Screen sizes ගණනාවකට responsive design support කරයි
- HTML attributes ට වඩා layout හි වැඩි control ලැඛේ
10.9 – CSS Syntax
/* selector { property: value; } */ p { color: blue; font-size: 16px; text-align: center; } /* selector = style කළ යුතු HTML element property = වෙනස් කළ යුතු දෙය (color, font-size, ආදිය) value = නව value Rules semicolons ; සමඟ අවසන් කෙරේ */
10.9.1 – CSS Styling ක්රම
10.9.1.1 – Inline CSS
Single HTML element වෙත style attribute භාවිතා කර සෘජුව apply කෙරේ.
<p style="color: red; font-size: 18px; font-weight: bold;"> මෙය red සහ bold paragraph. </p>
⊕ ඉක්මන් සහ specific. ⊖ Maintain කිරීමට අපහසු; styles reuse කළ නොහැකිය.
10.9.1.2 – Internal CSS
HTML file හි <head> section ඇතුළේ <style> tag ඇතුළේ CSS ලිවිය හැකිය.
<head> <style> body { background-color: #f0f0f0; font-family: Arial, sans-serif; } h1 { color: navy; text-align: center; } p { font-size: 16px; line-height: 1.6; } </style> </head>
⊕ Page එකේ elements සියල්ලට style. ⊖ Pages අතර styles share කළ නොහැකිය.
10.9.1.3 – External CSS
CSS file (.css) වෙනකක ලිවා HTML file හා link කෙරේ.
<head> <link rel="stylesheet" href="style.css"> </head>
body { background-color: white; font-family: Verdana, sans-serif; margin: 0; padding: 0; } h1 { color: #333333; text-align: center; } p { font-size: 15px; color: #555555; }
⊕ File එකක් සම්පූර්ණ website style කරයි. ⊕ Maintain කිරීම ලේසිම. හොඳම ක්රමය!
| ක්රමය | ලිවෙන ස්ථානය | Priority | හොඳම |
|---|---|---|---|
| Inline | HTML tag ඇතුළේ | ඉහළම | One-off styles |
| Internal | <style> in <head> | මධ්ය | Single page |
| External | වෙනම .css file | අඩුම | Pages කිහිපයකට (BEST) |
10.10.1 – Element Selector
Selects ALL elements of a specific HTML tag.
/* Styles ALL <p> elements */ p { color: blue; font-size: 14px; } /* Styles ALL <h1> elements */ h1 { color: red; }
10.10.2 – Group Selector
Applies the same styles to multiple selectors at once (separated by commas).
/* Same style for h1, h2, and h3 */ h1, h2, h3 { color: navy; font-family: Arial; } p, li, td { font-size: 14px; line-height: 1.5; }
10.10.3 – Class Selector (.)
Styles elements with a specific class attribute. Starts with a dot .
/* CSS */ .highlight { background-color: yellow; font-weight: bold; } .warning { color: red; border: 1px solid red; } /* HTML */ <p class="highlight">This is highlighted.</p> <p class="warning">This is a warning!</p> <!-- Multiple classes on one element: --> <p class="highlight warning">Both styles applied.</p>
10.10.4 – ID Selector (#)
Styles ONE specific element with a unique id. Starts with hash #. Each id must be unique on the page.
/* CSS */ #header { background-color: #003366; color: white; padding: 20px; text-align: center; } #footer { background-color: #333; color: #ccc; padding: 10px; } /* HTML */ <div id="header">Website Header</div> <div id="footer">Footer Text</div>
10.10.5 – Universal Selector (*)
Selects and styles ALL elements on the page.
/* Applies to every element */ * { margin: 0; padding: 0; box-sizing: border-box; }
| Selector | Syntax | Example | Targets |
|---|---|---|---|
| Element | tag | p { } | All <p> elements |
| Class | .classname | .red { } | All elements with class="red" |
| ID | #idname | #main { } | Element with id="main" |
| Universal | * | * { } | All elements |
| Group | a, b, c | h1, h2 { } | All listed elements |
10.10.1 – Element Selector
Specific HTML tag හි සියලු elements select කරයි.
/* සියලු <p> elements style කරයි */ p { color: blue; font-size: 14px; } /* සියලු <h1> elements style කරයි */ h1 { color: red; }
10.10.2 – Group Selector
Selectors කිහිපයකට (comma separated) එකවිට styles apply කරයි.
/* h1, h2, h3 සඳහා එකම style */ h1, h2, h3 { color: navy; font-family: Arial; } p, li, td { font-size: 14px; line-height: 1.5; }
10.10.3 – Class Selector (.)
Specific class attribute ඇති elements style කරයි. dot . සමඟ ආරම්භ වේ.
/* CSS */ .highlight { background-color: yellow; font-weight: bold; } .warning { color: red; border: 1px solid red; } /* HTML */ <p class="highlight">Highlighted paragraph.</p> <p class="warning">Warning paragraph!</p> <!-- Element හි multiple classes: --> <p class="highlight warning">Both styles applied.</p>
10.10.4 – ID Selector (#)
Unique id ඇති එකම element style කරයි. hash # සමඟ ආරම්භ. Page හි id unique විය යුතුය.
/* CSS */ #header { background-color: #003366; color: white; padding: 20px; text-align: center; } #footer { background-color: #333; color: #ccc; padding: 10px; } /* HTML */ <div id="header">Website Header</div> <div id="footer">Footer Text</div>
10.10.5 – Universal Selector (*)
Page හි සියලු elements select කර style කරයි.
/* සෑම element එකකටම apply වේ */ * { margin: 0; padding: 0; box-sizing: border-box; }
| Selector | Syntax | උදාහරණ | Target |
|---|---|---|---|
| Element | tag | p { } | සියලු <p> elements |
| Class | .classname | .red { } | class="red" ඇති elements |
| ID | #idname | #main { } | id="main_si" ඇති element |
| Universal | * | * { } | සියලු elements |
| Group | a, b, c | h1, h2 { } | Listed elements සියල්ල |
/* 10.11.1 Text Color */ p { color: red; } /* named colour */ p { color: #FF0000; } /* hex colour */ p { color: rgb(255, 0, 0); } /* RGB */ /* 10.11.2 Font Size */ h1 { font-size: 32px; } /* pixels */ p { font-size: 1.2em; } /* relative to parent */ body { font-size: 100%; } /* percentage */ /* 10.11.3 Font Family */ body { font-family: Arial, Helvetica, sans-serif; /* List fallback fonts — browser uses first available */ } /* 10.11.4 Text Align */ p { text-align: left; } /* default */ p { text-align: center; } p { text-align: right; } p { text-align: justify; } /* 10.11.5 Text Transform */ p { text-transform: uppercase; } /* ALL CAPS */ p { text-transform: lowercase; } /* all lower */ p { text-transform: capitalize; } /* First Letter */ /* 10.11.6 Text Decoration */ a { text-decoration: none; } /* remove underline from links */ p { text-decoration: underline; } p { text-decoration: line-through; } /* strikethrough */ p { text-decoration: overline; } /* 10.11.7 Font Style */ p { font-style: normal; } p { font-style: italic; } p { font-style: oblique; } /* 10.11.8 Background Color */ body { background-color: #ffffff; } div { background-color: lightblue; } /* 10.11.9 Background Image */ body { background-image: url("background.jpg"); background-repeat: no-repeat; /* repeat | repeat-x | repeat-y | no-repeat */ background-size: cover; /* cover | contain | auto | pixels */ background-position: center; /* top | bottom | left | right | center */ }
10.12 – CSS Comments
/* This is a single line CSS comment */ /* This is a multi-line CSS comment */
10.12.1 – CSS for Tables
table { width: 100%; border-collapse: collapse; /* removes double borders */ } th, td { border: 1px solid #ccc; padding: 10px; text-align: left; } th { background-color: #003366; color: white; } tr:nth-child(even) { background-color: #f2f2f2; /* zebra striping */ } tr:hover { background-color: #ddd; /* highlight row on hover */ }
10.12.2 – CSS for Images
img { width: 300px; height: auto; /* maintains aspect ratio */ border: 2px solid navy; border-radius: 8px; /* rounded corners */ display: block; margin: 0 auto; /* centre the image */ } img:hover { opacity: 0.8; transform: scale(1.05); }
/* 10.11.1 Text Color */ p { color: red; } /* named colour */ p { color: #FF0000; } /* hex colour */ p { color: rgb(255, 0, 0); } /* RGB */ /* 10.11.2 Font Size */ h1 { font-size: 32px; } /* pixels */ p { font-size: 1.2em; } /* parent relative */ body { font-size: 100%; } /* percentage */ /* 10.11.3 Font Family */ body { font-family: Arial, Helvetica, sans-serif; /* Fallback fonts — browser ලබාගත හැකි ප්රථම font භාවිතා කරයි */ } /* 10.11.4 Text Align */ p { text-align: left; } /* left | center | right | justify */ /* 10.11.5 Text Transform */ h2 { text-transform: uppercase; } /* UPPERCASE */ p { text-transform: capitalize; } /* First Letter Capitals */ p { text-transform: lowercase; } /* lowercase */ /* 10.11.6 Text Decoration */ a { text-decoration: none; } /* underline ඉවත් කරයි */ h3 { text-decoration: underline; } /* underline */ p { text-decoration: line-through; } /* strikethrough */ /* 10.11.7 Font Style */ p { font-style: italic; } /* italic text */ p { font-style: normal; } /* normal text */ /* 10.11.8 Background Color */ body { background-color: #f5f5f5; } div { background-color: rgba(0, 0, 255, 0.3); } /* opacity සහිත */ /* 10.11.9 Background Image */ body { background-image: url('background.jpg'); background-repeat: no-repeat; /* repeat-x | repeat-y | repeat */ background-size: cover; /* image cover කරයි */ background-position: center; }
CSS Comments
/* CSS comments මෙලෙස ලිවිය යුතුය */ /* Comment කිහිපු lines හරහා විය හැකිය HTML comments (<!-- -->) CSS හි ක්රියා නොකරයි */
Web authoring tools help create web pages without manually writing all the code.
| Tool | Type | Description |
|---|---|---|
| Notepad / Notepad++ | Text Editor | Free, simple; you write all HTML code manually |
| VS Code | Code Editor | Free, powerful with syntax highlighting and plugins |
| Sublime Text | Code Editor | Fast and lightweight code editor |
| Adobe Dreamweaver | WYSIWYG | Paid; visual design + code view; professional tool |
| WordPress | CMS | Content Management System; no coding needed |
| Wix / Squarespace | Website Builder | Drag-and-drop; hosted online |
WYSIWYG = What You See Is What You Get — the design view matches the final output.
| Tool | වර්ගය | විශේෂතා |
|---|---|---|
| Notepad | Text Editor | Windows built-in, සරල, HTML/CSS/PHP manual ලිවීමට |
| VS Code | Code Editor | Free, powerful, extensions, syntax highlighting |
| Sublime Text | Code Editor | ලෙහෙසි, ඉක්මන්, multiple cursor editing |
| Dreamweaver | WYSIWYG + Code | Adobe; visual design + code view දෙකම |
| WordPress | CMS | Coding නොමැතිව dynamic websites; themes, plugins |
| Wix | Online Builder | Drag-and-drop, beginners සඳහා, hosting included |
WYSIWYG = What You See Is What You Get — design view, final output සිදු ස..
10.15.1 – What is PHP?
PHP stands for PHP: Hypertext Preprocessor (recursive acronym). It is a popular server-side scripting language designed for web development.
- Created by Rasmus Lerdorf in 1994
- Free and open-source
- Runs on the server, not in the browser
- Outputs HTML that is sent to the browser
- Files have extension
.php - Works with databases (especially MySQL)
10.15.2 – Nature of a PHP File
- A PHP file can contain HTML, CSS, JavaScript, and PHP code
- PHP code is enclosed in
<?php ... ?>tags - The server processes PHP and sends pure HTML to the browser
- The user never sees the PHP source code
10.15.3 – What Can PHP Handle?
- Collect form data
- Generate dynamic page content
- Create, open, read, write, delete files on the server
- Add, delete, modify data in a database
- Control user access (login/logout)
- Encrypt data
- Send and receive cookies
- Send emails
10.15.4 – How PHP Works in Web Development
1. Browser requests: http://example.com/page.php 2. Web server receives request 3. PHP engine processes the .php file 4. PHP may query MySQL database 5. PHP generates HTML output 6. HTML is sent to browser 7. Browser displays the page
10.15.5 – Embedding PHP Code in a Web Page
<!DOCTYPE html> <html> <body> <h1>My PHP Page</h1> <?php // PHP code goes here echo "Hello, World!"; ?> <p>This is HTML again.</p> </body> </html>
echo outputs text/HTML to the browser. print also works (but returns 1).
10.15.6 – How to Use Comments in PHP
10.15.7.1 – Single Line Comments
<?php // This is a single-line comment # This is also a single-line comment echo "Hello"; // inline comment ?>
10.15.7.2 – Multi-line Comments
<?php /* This is a multi-line comment. It can span several lines. Used to describe functions, logic, etc. */ echo "PHP is great!"; ?>
10.15.8 – PHP Variables
Variables in PHP start with $ sign. They store data values.
- Variable names must start with a letter or underscore (not a number)
- Variable names are case-sensitive (
$name≠$Name) - No spaces in variable names
- PHP variables do NOT need to be declared with a type
<?php $name = "Kamal"; // string $age = 18; // integer $mark = 87.5; // double (float) $passed = true; // boolean // Output variables echo "Name: " . $name; // . = concatenation echo "Age: $age"; // variable inside double quotes is parsed echo "Mark: " . $mark . "\n"; // \n = newline (in HTML use <br>) ?>
10.15.9 – PHP Variable Types
10.15.9.1 – Integer
<?php $a = 10; $b = -5; $c = 1000; echo $a + $b; // 5 var_dump($a); // int(10) ?>
10.15.9.2 – Double (Float)
<?php $price = 9.99; $weight = 3.14159; echo $price; // 9.99 var_dump($price); // float(9.99) ?>
10.15.9.3 – Boolean
<?php $is_logged_in = true; $is_admin = false; var_dump($is_logged_in); // bool(true) // Used in conditions: if($is_logged_in) { ... } ?>
10.15.9.4 – String
<?php $first = "Hello"; $last = 'World'; // single or double quotes echo $first . " " . $last; // Hello World // Useful string functions: echo strlen($first); // 5 — length of string echo strtoupper($first); // HELLO echo strtolower($first); // hello echo str_replace("l", "r", $first); // Herro ?>
10.15.10 – Variable Scope
10.15.10.1 – Local Variables
Variables declared inside a function. Can only be used within that function.
<?php function myFunction() { $local_var = "I am local"; echo $local_var; // Works here } myFunction(); // echo $local_var; // ERROR! Not accessible outside ?>
10.15.10.2 – Global Variables
Variables declared outside functions. To use inside a function, use the global keyword.
<?php $x = 10; // global variable $y = 20; function add() { global $x, $y; // declare as global inside function echo $x + $y; // 30 } add(); ?>
10.15.10.3 – Static Variables
A local variable that keeps its value between function calls.
<?php function counter() { static $count = 0; // only initialised once $count++; echo $count . " "; } counter(); // 1 counter(); // 2 counter(); // 3 ?>
10.15.1 – PHP යනු කුමක්ද?
PHP = PHP: Hypertext Preprocessor (recursive acronym). Web development සඳහා නිර්මාණය කළ ජනප්රිය server-side scripting language ය.
- 1994 දී Rasmus Lerdorf විසින් නිර්මාණය කරන ලදී
- Free සහ open-source
- Browser හි නොව server හිදී ක්රියාත්මක වේ
- Browser වෙත HTML output කරයි
- Files extension:
.php - Databases (විශේෂයෙන් MySQL) සමඟ ක්රියා කරයි
10.15.2 – PHP File හි ස්වාභාවය
- PHP file හි HTML, CSS, JavaScript, සහ PHP code ඇතුළත් කළ හැකිය
- PHP code
<?php ... ?>tags ඇතුළේ ලිවිය යුතුය - Server PHP process කර browser වෙත pure HTML යවයි
- User ට PHP source code කිසිදා නොපෙනේ
10.15.3 – PHP හට Handle කළ හැකි දේ
- Form data collect කිරීම
- Dynamic page content generate කිරීම
- Server හි files create, open, read, write, delete කිරීම
- Database හි data add, delete, modify කිරීම
- User access control (login/logout)
- Data encrypt කිරීම
- Cookies send/receive කිරීම
- Emails send කිරීම
10.15.4 – Web Development හි PHP ක්රියා කරන ආකාරය
1. Browser requests: http://example.com/page.php 2. Web server request receive කරයි 3. PHP engine .php file process කරයි 4. PHP, MySQL database query කළ හැකිය 5. PHP, HTML output generate කරයි 6. HTML browser වෙත send කෙරේ 7. Browser page display කරයි
10.15.5 – Web Page හි PHP Code Embed කිරීම
<!DOCTYPE html> <html> <body> <h1>My PHP Page</h1> <?php // PHP code මෙහි ලිවිය යුතුය echo "Hello, World!"; ?> <p>HTML නැවතත් ආරම්භ වේ.</p> </body> </html>
echo text/HTML browser වෙත output කරයි. print ද ක්රියා කරයි (නමුත් 1 return කරයි).
10.15.6 – PHP හි Comments භාවිතය
10.15.7.1 – Single Line Comments
<?php // Single-line comment # Single-line comment (වෙනත් ස්වරූපය) echo "Hello"; // inline comment ?>
10.15.7.2 – Multi-line Comments
<?php /* Multi-line comment. Lines කිහිපයකින් ලිවිය හැකිය. Functions, logic විස්තර කිරීමට. */ echo "PHP is great!"; ?>
10.15.8 – PHP Variables
PHP හි variables $ sign සමඟ ආරම්භ වේ. Data values ගබඩා කරයි.
- Variable names letter හෝ underscore සමඟ ආරම්භ විය යුතුය (number සමඟ නොවේ)
- Variable names case-sensitive (
$name≠$Name) - Variable names හි spaces නොමැත
- PHP variables type declare කිරීම අවශ්ය නොවේ
<?php $name = "Kamal"; // string $age = 18; // integer $mark = 87.5; // double (float) $passed = true; // boolean // Variables output කිරීම echo "Name: " . $name; // . = concatenation echo "Age: $age"; // double quotes ඇතුළේ parse වේ echo "Mark: " . $mark . "\n"; // \n = newline (HTML: <br>) ?>
10.15.9 – PHP Variable Types (Data Types)
10.15.9.1 – Integer (පූර්ණ සංඛ්යා)
<?php $a = 10; $b = -5; $c = 1000; echo $a + $b; // 5 var_dump($a); // int(10) ?>
10.15.9.2 – Double / Float (දශමාංශ සංඛ්යා)
<?php $price = 9.99; $weight = 3.14159; echo $price; // 9.99 var_dump($price); // float(9.99) ?>
10.15.9.3 – Boolean (සත්ය/අසත්ය)
<?php $is_logged_in = true; $is_admin = false; var_dump($is_logged_in); // bool(true) // Conditions හි: if($is_logged_in) { ... } ?>
10.15.9.4 – String (text)
<?php $first = "Hello"; $last = 'World'; // single හෝ double quotes echo $first . " " . $last; // Hello World // String functions: echo strlen($first); // 5 — string length echo strtoupper($first); // HELLO echo strtolower($first); // hello echo str_replace("l", "r", $first); // Herro ?>
10.15.10 – Variable Scope
10.15.10.1 – Local Variables
Function ඇතුළේ declare කළ variables. එම function ඇතුළේ පමණක් භාවිතා කළ හැකිය.
<?php function myFunction() { $local_var = "මා local"; echo $local_var; // ඇතුළේ ක්රියා කරයි } myFunction(); // echo $local_var; // ERROR! ඉවතින් access නොවේ ?>
10.15.10.2 – Global Variables
Functions ඉවතින් declare කළ variables. Function ඇතුළේ භාවිතා කිරීමට global keyword භාවිතා කළ යුතුය.
<?php $x = 10; // global variable $y = 20; function add() { global $x, $y; // function ඇතුළේ global ලෙස declare echo $x + $y; // 30 } add(); ?>
10.15.10.3 – Static Variables
Function calls අතර value ගබඩා කරගන්නා local variable.
<?php function counter() { static $count = 0; // එක් වරක් පමණ initialise $count++; echo $count . " "; } counter(); // 1 counter(); // 2 counter(); // 3 ?>
An array stores multiple values in a single variable. Think of it as a list.
10.16.1.1 – Numeric (Indexed) Array
Elements are accessed by a numeric index starting at 0.
<?php // Method 1: array() function $fruits = array("Apple", "Mango", "Banana"); // Method 2: Short syntax (PHP 5.4+) $fruits = ["Apple", "Mango", "Banana"]; // Access elements by index echo $fruits[0]; // Apple echo $fruits[1]; // Mango echo $fruits[2]; // Banana // Useful array functions echo count($fruits); // 3 — number of elements $fruits[] = "Papaya"; // adds to end sort($fruits); // sort alphabetically print_r($fruits); // print full array ?>
10.16.1.2 – Associative Array
Uses named keys instead of numbers. Key-value pairs.
<?php $student = [ "name" => "Kamal", "age" => 18, "city" => "Colombo", "grade" => "A" ]; // Access by key name echo $student["name"]; // Kamal echo $student["age"]; // 18 echo $student["grade"]; // A // Modify a value $student["city"] = "Kandy"; // Loop through with foreach foreach ($student as $key => $value) { echo $key . ": " . $value . "<br>"; } ?>
10.16.1.3 – Multidimensional Array
An array containing other arrays (array of arrays).
<?php $students = [ ["Kamal", 85, "A"], ["Nimal", 72, "B"], ["Sunil", 91, "A+"] ]; // Access with [row][column] echo $students[0][0]; // Kamal echo $students[1][1]; // 72 echo $students[2][2]; // A+ // Associative multidimensional $class = [ "student1" => ["name" => "Kamal", "marks" => 85], "student2" => ["name" => "Nimal", "marks" => 72] ]; echo $class["student1"]["name"]; // Kamal echo $class["student2"]["marks"]; // 72 ?>
Array එකක් variable එකක multiple values ගබඩා කරයි. ලැයිස්තුවක් ලෙස සිතන්න.
10.16.1.1 – Numeric (Indexed) Array
Elements 0 සිට ආරම්භ වන numeric index මගින් access කෙරේ.
<?php // ක්රමය 1: array() function $fruits = array("Apple", "Mango", "Banana"); // ක්රමය 2: Short syntax (PHP 5.4+) $fruits = ["Apple", "Mango", "Banana"]; // Index මගින් access echo $fruits[0]; // Apple echo $fruits[1]; // Mango echo $fruits[2]; // Banana // Array functions echo count($fruits); // 3 — elements ගණන $fruits[] = "Papaya"; // අගට add කරයි sort($fruits); // alphabetically sort කරයි print_r($fruits); // සම්පූර්ණ array print කරයි ?>
10.16.1.2 – Associative Array
Numbers වෙනුවට named keys භාවිතා කරයි. Key-value pairs.
<?php $student = [ "name" => "Kamal", "age" => 18, "city" => "Colombo", "grade" => "A" ]; // Key name මගින් access echo $student["name"]; // Kamal echo $student["age"]; // 18 echo $student["grade"]; // A // Value modify කිරීම $student["city"] = "Kandy"; // foreach සමඟ iterate කිරීම foreach ($student as $key => $value) { echo $key . ": " . $value . "<br>"; } ?>
10.16.1.3 – Multidimensional Array
Arrays ඇතුළේ arrays — 2D table ලෙස සිතන්න.
<?php $students = [ ["Kamal", 18, "A"], ["Nimal", 19, "B"], ["Sunil", 17, "A"] ]; echo $students[0][0]; // Kamal (row 0, column 0) echo $students[1][2]; // B (row 1, column 2) // Associative 2D array $records = [ ["name" => "Kamal", "grade" => "A"], ["name" => "Nimal", "grade" => "B"] ]; echo $records[0]["name"]; // Kamal ?>
10.17.1 – PHP Selection Statements
10.17.1.1 – If Statement
<?php $age = 18; if ($age >= 18) { echo "You are an adult."; } ?>
10.17.1.2 – If...Else Statement
<?php $marks = 55; if ($marks >= 50) { echo "Pass"; } else { echo "Fail"; } ?>
10.17.1.3 – If...Elseif...Else
<?php $marks = 72; if ($marks >= 75) { echo "Distinction"; } elseif ($marks >= 65) { echo "Merit"; } elseif ($marks >= 50) { echo "Pass"; } else { echo "Fail"; } ?>
== (equal), != (not equal), > (greater), < (less), >= (greater or equal), <= (less or equal), === (identical — same value AND type)
10.17.2 – Loop Control Structures
10.17.2.1 – While Loop
Repeats a block of code while a condition is true. Condition checked before the loop body.
<?php $i = 1; while ($i <= 5) { echo "Number: " . $i . "<br>"; $i++; // IMPORTANT: must increment to avoid infinite loop! } /* Output: Number: 1 Number: 2 Number: 3 Number: 4 Number: 5 */ ?>
10.17.2.2 – Do...While Loop
Condition checked after the loop body — so the code runs at least once.
<?php $i = 1; do { echo "Value: " . $i . "<br>"; $i++; } while ($i <= 5); /* Even if condition is false initially, runs at least ONCE: $i = 10; do { echo $i; $i++; } while ($i < 5); // prints 10 (runs once!) */ ?>
10.17.2.3 – For Loop
Used when you know exactly how many times to repeat. Most compact loop structure.
<?php // Syntax: for(initialise; condition; increment) for ($i = 1; $i <= 10; $i++) { echo $i . " "; } // Output: 1 2 3 4 5 6 7 8 9 10 // Counting down for ($i = 10; $i >= 1; $i--) { echo $i . " "; } // Output: 10 9 8 7 6 5 4 3 2 1 // Loop through array with for $fruits = ["Apple", "Mango", "Banana"]; for ($i = 0; $i < count($fruits); $i++) { echo $fruits[$i] . "<br>"; } ?>
| Loop | When to use | Condition check |
|---|---|---|
while | Unknown number of repetitions | Before body (may not run at all) |
do...while | Must run at least once | After body |
for | Known number of repetitions | Before body |
foreach | Iterate arrays | Automatic |
10.17.1 – Selection Control Structures
10.17.1.1 – If Statement
Condition එකක් true නම් පමණක් code execute කරයි.
<?php $age = 18; if ($age >= 18) { echo "ඔබ වැඩිහිටියෙකි."; } ?>
10.17.1.2 – If...Else Statement
<?php $marks = 55; if ($marks >= 50) { echo "Pass"; } else { echo "Fail"; } ?>
10.17.1.3 – If...Elseif...Else
<?php $marks = 72; if ($marks >= 75) { echo "Distinction"; } elseif ($marks >= 65) { echo "Merit"; } elseif ($marks >= 50) { echo "Pass"; } else { echo "Fail"; } ?>
== (සමාන), != (සමාන නෙමෙ), > (වැඩි), < (අඩු), >= (වැඩි හෝ සමාන), <= (අඩු හෝ සමාන), === (identical — value AND type දෙකම සමාන)
10.17.2 – Loop Control Structures
10.17.2.1 – While Loop
Condition true වන තාක් code repeat කරයි. Loop body ට පෙර condition check කෙරේ.
<?php $i = 1; while ($i <= 5) { echo "Number: " . $i . "<br>"; $i++; // වැදගත්: infinite loop නොවීමට increment කළ යුතුය! } /* Output: Number: 1 Number: 2 Number: 3 Number: 4 Number: 5 */ ?>
10.17.2.2 – Do...While Loop
Loop body ට පසු condition check කෙරේ — code අවම වශයෙන් එක් වරක් ක්රියා කරයි.
<?php $i = 1; do { echo "Value: " . $i . "<br>"; $i++; } while ($i <= 5); /* Condition false වුනත් අවම වශයෙන් ONCE ක්රියා කරයි: $i = 10; do { echo $i; $i++; } while ($i < 5); // 10 print කරයි! */ ?>
10.17.2.3 – For Loop
කීවිලාවක් repeat කළ යුතුදැයි දන්නා විට. Compact loop structure.
<?php // Syntax: for(initialise; condition; increment) for ($i = 1; $i <= 10; $i++) { echo $i . " "; } // Output: 1 2 3 4 5 6 7 8 9 10 // Counting down for ($i = 10; $i >= 1; $i--) { echo $i . " "; } // Output: 10 9 8 7 6 5 4 3 2 1 // for loop සමඟ array iterate $fruits = ["Apple", "Mango", "Banana"]; for ($i = 0; $i < count($fruits); $i++) { echo $fruits[$i] . "<br>"; } ?>
| Loop | භාවිතා කළ යුත්තේ | Condition Check |
|---|---|---|
while | Repetitions ගණන නොදන්නා විට | Body ට පෙර (ශූන්ය වාරයක් ද ක්රියා නොකිරීමට ඉඩ ඇත) |
do...while | අවම වශයෙන් එක් වරක් ක්රියා කළ යුතු විට | Body ට පසු |
for | Repetitions ගණන දන්නා විට | Body ට පෙර |
foreach | Arrays iterate කිරීමට | ස්වයංක්රීය |
The foreach loop is designed specifically for iterating over arrays. It automatically goes through each element.
<?php // ── Numeric Array ── $colors = ["Red", "Green", "Blue"]; foreach ($colors as $color) { echo $color . "<br>"; } /* Output: Red Green Blue */ // ── Associative Array (with key) ── $student = ["name" => "Kamal", "age" => 18, "city" => "Colombo"]; foreach ($student as $key => $value) { echo "<b>" . $key . "</b>: " . $value . "<br>"; } /* Output: name: Kamal age: 18 city: Colombo */ // ── Display array as HTML table ── $marks = ["Maths" => 85, "ICT" => 92, "English" => 78]; echo "<table border='1'><tr><th>Subject</th><th>Marks</th></tr>"; foreach ($marks as $subject => $mark) { echo "<tr><td>" . $subject . "</td><td>" . $mark . "</td></tr>"; } echo "</table>"; ?>
foreach loop arrays iterate කිරීමට විශේෂිතව නිර්මාණය කෙරේ. ස්වයංක්රීයව සෑම element හරහා යාවිසේ.
<?php // ── Numeric Array ── $colors = ["Red", "Green", "Blue"]; foreach ($colors as $color) { echo $color . "<br>"; } /* Output: Red Green Blue */ // ── Associative Array (key සමඟ) ── $student = ["name" => "Kamal", "age" => 18, "city" => "Colombo"]; foreach ($student as $key => $value) { echo "<b>" . $key . "</b>: " . $value . "<br>"; } /* Output: name: Kamal age: 18 city: Colombo */ // ── HTML table ලෙස array display ── $marks = ["Maths" => 85, "ICT" => 92, "English" => 78]; echo "<table border='1'><tr><th>Subject</th><th>Marks</th></tr>"; foreach ($marks as $subject => $mark) { echo "<tr><td>" . $subject . "</td><td>" . $mark . "</td></tr>"; } echo "</table>"; ?>
A function is a reusable block of code that performs a specific task. You define it once and call it multiple times.
10.19.1 – User Defined Functions
<?php // Define a function function greet() { echo "Hello! Welcome to our website.<br>"; } // Call the function greet(); // Output: Hello! Welcome to our website. greet(); // Can call multiple times ?>
10.19.2 – Function Arguments (Parameters)
Functions can accept parameters (input values) and can return values.
<?php // Function with parameters function greetUser($name, $city) { echo "Hello, $name! You are from $city.<br>"; } greetUser("Kamal", "Colombo"); // Hello, Kamal! You are from Colombo. greetUser("Nimal", "Kandy"); // Hello, Nimal! You are from Kandy. // Function with return value function add($a, $b) { return $a + $b; } $result = add(10, 20); echo "Sum: " . $result; // Sum: 30 // Function with default parameter function power($base, $exp = 2) { // exp defaults to 2 return $base ** $exp; } echo power(3); // 9 (3^2) echo power(2, 8); // 256 (2^8) // ── Practical example: calculate grade ── function getGrade($marks) { if ($marks >= 75) return "A"; elseif ($marks >= 65) return "B"; elseif ($marks >= 50) return "C"; else return "F"; } echo getGrade(80); // A echo getGrade(45); // F ?>
Function එකක් specific task එකක් ඉටු කරන reusable code block. එක් වරක් define කර කිහිප වරක් call කළ හැකිය.
10.19.1 – User Defined Functions
<?php // Function define කිරීම function greet() { echo "Hello! Welcome to our website.<br>"; } // Function call කිරීම greet(); // Output: Hello! Welcome to our website. greet(); // කිහිප වරක් call කළ හැකිය ?>
10.19.2 – Function Arguments (Parameters)
Functions parameters (input values) accept කළ හැකි අතර values return ද කළ හැකිය.
<?php // Parameters සහිත function function greetUser($name, $city) { echo "Hello, $name! ඔබ $city සිටිනා.<br>"; } greetUser("Kamal", "Colombo"); greetUser("Nimal", "Kandy"); // Return value සහිත function function add($a, $b) { return $a + $b; } $result = add(10, 20); echo "Sum: " . $result; // Sum: 30 // Default parameter සහිත function function power($base, $exp = 2) { // exp default: 2 return $base ** $exp; } echo power(3); // 9 (3^2) echo power(2, 8); // 256 (2^8) // ── Practical: grade calculate ── function getGrade($marks) { if ($marks >= 75) return "A"; elseif ($marks >= 65) return "B"; elseif ($marks >= 50) return "C"; else return "F"; } echo getGrade(80); // A echo getGrade(45); // F ?>
MySQL is the most popular Relational Database Management System (RDBMS) used with PHP. Data is stored in tables (rows and columns).
http://localhost/phpmyadmin10.20.1 – Create MySQL Database
-- Using phpMyAdmin SQL tab, or MySQL command line: CREATE DATABASE school_db; USE school_db;
10.20.2 – Create the Table
CREATE TABLE students ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, age INT, city VARCHAR(50), marks FLOAT, email VARCHAR(100) ); -- Common MySQL Data Types: -- INT = whole numbers -- FLOAT = decimal numbers -- VARCHAR(n) = text up to n characters -- TEXT = long text -- DATE = date (YYYY-MM-DD) -- BOOLEAN = true/false (stored as 1/0) -- AUTO_INCREMENT = number increases automatically -- PRIMARY KEY = unique identifier for each row
10.20.3 – Working with Database
PHP to MySQL Connection
<?php // Database connection settings $host = "localhost"; $username = "root"; // default MySQL username in XAMPP $password = ""; // default is empty in XAMPP $database = "school_db"; // Create connection $conn = new mysqli($host, $username, $password, $database); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully!"; ?>
10.20.3.1 – Add Data into Database (INSERT)
<?php // 1. Connect to database (assume connection above) $conn = new mysqli("localhost", "root", "", "school_db"); // 2. Data to insert $name = "Kamal Silva"; $age = 18; $city = "Colombo"; $marks = 85.5; // 3. SQL INSERT statement $sql = "INSERT INTO students (name, age, city, marks) VALUES ('$name', $age, '$city', $marks)"; // 4. Execute and check if ($conn->query($sql) === TRUE) { echo "Record inserted successfully! ID: " . $conn->insert_id; } else { echo "Error: " . $conn->error; } $conn->close(); // close connection ?>
Full Form + Insert Example
<!-- form.html --> <form action="insert.php" method="post"> Name: <input type="text" name="name"><br> Age: <input type="number" name="age"><br> City: <input type="text" name="city"><br> Marks: <input type="number" name="marks"><br> <input type="submit" value="Add Student"> </form> <!-- insert.php --> <?php $conn = new mysqli("localhost", "root", "", "school_db"); $name = $_POST["name"]; // retrieve POST data $age = $_POST["age"]; $city = $_POST["city"]; $marks = $_POST["marks"]; $sql = "INSERT INTO students (name, age, city, marks) VALUES ('$name', '$age', '$city', '$marks')"; if ($conn->query($sql)) { echo "Student added successfully!"; } else { echo "Error: " . $conn->error; } $conn->close(); ?>
10.20.3.2 – Retrieve and Display Data (SELECT)
<?php $conn = new mysqli("localhost", "root", "", "school_db"); // SQL SELECT statement $sql = "SELECT * FROM students"; $result = $conn->query($sql); if ($result->num_rows > 0) { echo "<table border='1'>"; echo "<tr><th>ID</th><th>Name</th><th>Age</th><th>City</th><th>Marks</th></tr>"; // Fetch each row as associative array while ($row = $result->fetch_assoc()) { echo "<tr>"; echo "<td>" . $row["id"] . "</td>"; echo "<td>" . $row["name"] . "</td>"; echo "<td>" . $row["age"] . "</td>"; echo "<td>" . $row["city"] . "</td>"; echo "<td>" . $row["marks"] . "</td>"; echo "</tr>"; } echo "</table>"; } else { echo "No records found."; } $conn->close(); ?>
More SQL Commands You Need to Know
-- SELECT specific columns SELECT name, marks FROM students; -- SELECT with condition (WHERE) SELECT * FROM students WHERE city = 'Colombo'; SELECT * FROM students WHERE marks > 80; -- SELECT ordered SELECT * FROM students ORDER BY marks DESC; SELECT * FROM students ORDER BY name ASC; -- UPDATE record UPDATE students SET city = 'Galle' WHERE id = 1; -- DELETE record DELETE FROM students WHERE id = 3; -- Count records SELECT COUNT(*) FROM students; -- Limit results SELECT * FROM students LIMIT 5;
• Create = INSERT INTO
• Read = SELECT FROM
• Update = UPDATE ... SET ... WHERE
• Delete = DELETE FROM ... WHERE
Always include WHERE in UPDATE and DELETE — without it, ALL records are affected!
Complete Student Management System
<!DOCTYPE html> <html> <head><title>Student System</title></head> <body> <h2>Add Student</h2> <form method="post"> <input type="text" name="name" placeholder="Name"> <input type="number" name="marks" placeholder="Marks"> <input type="submit" name="add" value="Add"> </form> <?php $conn = new mysqli("localhost", "root", "", "school_db"); // Insert if form submitted if (isset($_POST["add"])) { $name = $_POST["name"]; $marks = $_POST["marks"]; $conn->query("INSERT INTO students (name, marks) VALUES ('$name', $marks)"); echo "<p style='color:green'>Added!</p>"; } // Display all students echo "<h2>All Students</h2><table border='1'>"; echo "<tr><th>ID</th><th>Name</th><th>Marks</th></tr>"; $res = $conn->query("SELECT * FROM students ORDER BY id"); while ($row = $res->fetch_assoc()) { echo "<tr><td>{$row['id']}</td><td>{$row['name']}</td><td>{$row['marks']}</td></tr>"; } echo "</table>"; $conn->close(); ?> </body> </html>
MySQL PHP සමඟ භාවිතා කරන ජනප්රිය Relational Database Management System (RDBMS). Data tables (rows සහ columns) හි ගබඩා කෙරේ.
http://localhost/phpmyadmin10.20.1 – MySQL Database නිර්මාණය
-- phpMyAdmin SQL tab හෝ MySQL command line: CREATE DATABASE school_db; USE school_db;
10.20.2 – Table නිර්මාණය
CREATE TABLE students ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, age INT, city VARCHAR(50), marks FLOAT, email VARCHAR(100) ); -- MySQL Data Types: -- INT = පූර්ණ සංඛ්යා -- FLOAT = දශමාංශ සංඛ්යා -- VARCHAR(n) = n characters දක්වා text -- TEXT = දිගු text -- DATE = දිනය (YYYY-MM-DD) -- BOOLEAN = true/false (1/0 ලෙස ගබඩා) -- AUTO_INCREMENT = ස්වයංක්රීයව number increase -- PRIMARY KEY = සෑම row හඳුනාගන්නා unique id
10.20.3 – Database සමඟ වැඩ කිරීම
<?php $host = "localhost"; $username = "root"; // XAMPP default $password = ""; // XAMPP default (password නෑ) $database = "school_db"; $conn = new mysqli($host, $username, $password, $database); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully!"; ?>
<?php // Form data ලබාගෙන INSERT කිරීම $name = $_POST["name"]; $age = $_POST["age"]; $city = $_POST["city"]; $marks = $_POST["marks"]; $sql = "INSERT INTO students (name, age, city, marks) VALUES ('$name', '$age', '$city', '$marks')"; if ($conn->query($sql) === true) { echo "Record insert සාර්ථකයි!"; } else { echo "Error: " . $conn->error; } ?>
<?php $sql = "SELECT * FROM students"; $result = $conn->query($sql); echo "<table border='1'>"; echo "<tr><th>ID</th><th>Name</th><th>Age</th><th>City</th><th>Marks</th></tr>"; while ($row = $result->fetch_assoc()) { echo "<tr>"; echo "<td>" . $row["id"] . "</td>"; echo "<td>" . $row["name"] . "</td>"; echo "<td>" . $row["age"] . "</td>"; echo "<td>" . $row["city"] . "</td>"; echo "<td>" . $row["marks"] . "</td>"; echo "</tr>"; } echo "</table>"; $conn->close(); ?>
SQL Commands — CRUD Operations
| Operation | SQL Command | විස්තරය |
|---|---|---|
| Create | INSERT INTO | නව record add |
| Read | SELECT | Records retrieve |
| Update | UPDATE | Records update |
| Delete | DELETE | Records delete |
-- WHERE clause සමඟ SELECT SELECT * FROM students WHERE marks > 50; SELECT * FROM students ORDER BY marks DESC; SELECT * FROM students LIMIT 10; -- UPDATE (WHERE නොමැතිව සියලු records update වේ!) UPDATE students SET city = 'Kandy' WHERE id = 1; -- DELETE (WHERE නොමැතිව සියලු records delete වේ!) DELETE FROM students WHERE id = 5; -- COUNT SELECT COUNT(*) FROM students;
This activity applies every concept from 10.20 (Database Connectivity) to build a complete, working web application from scratch. You will create four PHP files that together form a Student Registration System for a school ICT lab.
C:\xampp\htdocs\phpActivity\ and opened via http://localhost/phpActivity/10.21.1 – Activity Overview
Scenario
The ICT teacher at Vidyaloka School needs a simple web-based system to store student details. The system must allow staff to add new students (name, age, city, marks) and view all students in a table with their calculated grade.
Files to Create
| File | Purpose | Main SQL / PHP Concept |
|---|---|---|
setup_db.php | Create database and table | CREATE DATABASE, CREATE TABLE |
connect.php | Reusable connection file | new mysqli(), require_once |
insert.php | HTML form + save to database | $_POST, INSERT INTO |
retrieve.php | Display all students | SELECT *, fetch_assoc() |
Database Structure — school_db → students table
| Column | Data Type | Description |
|---|---|---|
id | INT AUTO_INCREMENT PRIMARY KEY | Unique row number — set automatically, never entered manually |
name | VARCHAR(100) NOT NULL | Student name — text up to 100 characters, required |
age | INT | Student age — whole number |
city | VARCHAR(50) | City or town — text up to 50 characters |
marks | FLOAT | Exam marks — decimal number (e.g. 85.5) |
INT (whole number), FLOAT (decimal), VARCHAR(n) (text, max n chars), TEXT (long text), DATE (YYYY-MM-DD), AUTO_INCREMENT (auto-increase), PRIMARY KEY (unique identifier for each row).10.21.2 – Step 0 — setup_db.php (Create Database & Table)
This is the very first file to run. It creates the school_db database and the students table automatically. You only need to run it once at the beginning of the activity.
Full Script — setup_db.php
<?php // Step 1 — Connect to MySQL WITHOUT selecting a database $conn = new mysqli("localhost", "root", ""); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Step 2 — Create the database $conn->query("CREATE DATABASE IF NOT EXISTS school_db"); echo "Database school_db is ready.<br>"; // Step 3 — Switch into the new database $conn->select_db("school_db"); // Step 4 — Create the students table $sql = "CREATE TABLE IF NOT EXISTS students ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, age INT, city VARCHAR(50), marks FLOAT )"; $conn->query($sql); echo "Table students is ready.<br>"; // Step 5 — Show current row count $result = $conn->query("SELECT COUNT(*) AS total FROM students"); $row = $result->fetch_assoc(); echo "Total records: " . $row["total"]; $conn->close(); ?>
Code Explained — Line by Line
| Code | Explanation |
|---|---|
new mysqli("localhost","root","") | Connects to MySQL with only 3 arguments — no database name, because it does not exist yet |
$conn->connect_error | Contains the error text if connection failed; empty (falsy) if successful |
die("...") | Stops the script immediately and prints the message — used to handle fatal errors |
CREATE DATABASE IF NOT EXISTS | Creates the database — IF NOT EXISTS prevents an error if you run the page a second time |
$conn->select_db("school_db") | Switches the active database — same as typing USE school_db; in SQL |
CREATE TABLE IF NOT EXISTS | Creates the table only if it does not already exist |
INT AUTO_INCREMENT PRIMARY KEY | The id column increases automatically — MySQL assigns it; you never insert it manually |
VARCHAR(100) NOT NULL | Text field, max 100 characters — NOT NULL means this column cannot be left empty |
SELECT COUNT(*) AS total | Counts all rows in the table — AS total names the result column so we can read it as $row["total"] |
$conn->close() | Closes the database connection and frees MySQL resources |
10.21.3 – Step 1 — connect.php (Database Connection)
This file stores the database connection details. Every other PHP file includes it using require_once so the connection code is written only once and reused everywhere.
Full Script — connect.php
<?php // Database connection settings $host = "localhost"; // MySQL server (same machine as Apache) $username = "root"; // default XAMPP username $password = ""; // default XAMPP password (empty) $database = "school_db"; // the database created in Step 0 // Create connection — 4 arguments: host, user, password, database $conn = new mysqli($host, $username, $password, $database); // Check connection — stop script if it fails if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?>
mysqli() Parameters
| Parameter | Value (XAMPP Default) | Meaning |
|---|---|---|
| $host | "localhost" | MySQL server runs on the same computer as Apache |
| $username | "root" | Default admin user created automatically by XAMPP |
| $password | "" | XAMPP sets no password for root by default |
| $database | "school_db" | Must exactly match the database name created in Step 0 |
How Other Files Include connect.php
<?php // Written at the top of insert.php and retrieve.php: require_once "connect.php"; // After this one line, $conn is available and ready to use. // No need to repeat new mysqli() in every file. ?>
require_once includes the file exactly once. If the file is missing, PHP stops with a fatal error. This is intentional — without a connection, the rest of the script cannot work.10.21.4 – Step 2 — insert.php (HTML Form + INSERT INTO)
This file has two parts in the same file:
- Part A (PHP at the top) — runs only when the form is submitted; reads
$_POSTdata and saves it to MySQL. - Part B (HTML below) — the form the user fills in; always displayed.
Page Flow
| Event | REQUEST_METHOD | What PHP does |
|---|---|---|
User opens insert.php for the first time | GET | PHP block is skipped — only the HTML form is shown |
| User fills form and clicks Submit | — | Browser sends form data to insert.php via POST |
| Page reloads with the submitted data | POST | PHP block runs → data saved → success message shown → form shown again |
Full Script — insert.php
<?php // Part A — runs ONLY when the form is submitted (POST) if ($_SERVER["REQUEST_METHOD"] == "POST") { require_once "connect.php"; // open DB connection // Read form values sent by the browser $name = $_POST["name"]; $age = $_POST["age"]; $city = $_POST["city"]; $marks = $_POST["marks"]; // Build the SQL INSERT statement $sql = "INSERT INTO students (name, age, city, marks) VALUES ('"$name', $age, '"$city', $marks")"; // Execute the query if ($conn->query($sql) === TRUE) { $id = $conn->insert_id; // AUTO_INCREMENT id assigned to the new row echo "<p style='color:green'>Student added successfully! ID = $id</p>"; } else { echo "<p style='color:red'>Error: " . $conn->error . "</p>"; } $conn->close(); } ?> <!-- Part B — HTML Form (always displayed) --> <form method="post" action="insert.php"> Name: <input type="text" name="name" required><br> Age: <input type="number" name="age" required><br> City: <input type="text" name="city" required><br> Marks: <input type="number" name="marks" required><br> <input type="submit" value="Save Student"> </form>
Key PHP Concepts in insert.php
| Code | Explanation |
|---|---|
$_SERVER["REQUEST_METHOD"] | Contains "GET" when page first loads; contains "POST" after the form is submitted |
$_POST["name"] | Reads the value of the <input name="name"> field — the name attribute must match exactly |
INSERT INTO students (cols) VALUES (vals) | SQL to add a new row — text values need single quotes '$name'; number values do not $age |
$conn->query($sql) === TRUE | INSERT returns true on success (not a result set) — use === for strict comparison |
$conn->insert_id | The AUTO_INCREMENT id MySQL assigned to the newly inserted row |
$conn->error | Contains the MySQL error message if the last query failed |
Key HTML Form Attributes in insert.php
| Attribute | Value | Explanation |
|---|---|---|
method | "post" | Sends data in the HTTP request body — values are hidden from the URL |
action | "insert.php" | The file that receives and processes the submitted data |
name="name" | any text | Becomes the key in $_POST["name"] — must match exactly |
type="number" | — | Browser only accepts numeric input in this field |
required | — | Browser blocks form submission if the field is empty |
'$name'. Number values (age, marks) must NOT have quotes: $age. Mixing these up will cause a MySQL error.10.21.5 – Step 3 — retrieve.php (SELECT + Display Table)
This file fetches every row from the students table using SELECT * and displays the results in an HTML table. It also calculates each student's grade using if-elseif-else — the grade is not stored in the database; it is computed live by PHP each time the page loads.
Full Script — retrieve.php
<?php require_once "connect.php"; // reuse the same connection file // SELECT all rows, sorted by marks highest first $sql = "SELECT * FROM students ORDER BY marks DESC"; $result = $conn->query($sql); echo "Total students: " . $result->num_rows . "<br>"; if ($result->num_rows > 0) { echo "<table border='1'>"; echo "<tr><th>ID</th><th>Name</th><th>Age</th>"; echo "<th>City</th><th>Marks</th><th>Grade</th></tr>"; // Loop — fetch one row at a time until no more rows remain while ($row = $result->fetch_assoc()) { $id = $row["id"]; $name = $row["name"]; $age = $row["age"]; $city = $row["city"]; $marks = $row["marks"]; // Calculate grade from marks using if-elseif-else if ($marks >= 75) { $grade = "A"; } elseif ($marks >= 65) { $grade = "B"; } elseif ($marks >= 50) { $grade = "C"; } else { $grade = "F"; } echo "<tr>"; echo "<td>$id</td><td>$name</td><td>$age</td>"; echo "<td>$city</td><td>$marks</td><td>$grade</td>"; echo "</tr>"; } echo "</table>"; } else { echo "No students added yet."; } $conn->close(); ?>
Key PHP Concepts in retrieve.php
| Code | Explanation |
|---|---|
$conn->query($sql) | For SELECT, this returns a result set object — not just true/false like INSERT |
$result->num_rows | The number of rows returned by the SELECT query |
while ($row = $result->fetch_assoc()) | Fetches the next row as an associative array; returns null when no more rows — loop ends automatically |
$row["name"] | Gets the value of the name column in the current row — key must match the column name exactly |
ORDER BY marks DESC | Sorts results from highest marks to lowest — use ASC for lowest to highest |
How fetch_assoc() Reads the Result Set
| Loop call | $row returned by fetch_assoc() |
|---|---|
| 1st iteration | ["id"=>1, "name"=>"Kamal Silva", "age"=>18, "city"=>"Colombo", "marks"=>85] |
| 2nd iteration | ["id"=>2, "name"=>"Nimal Perera", "age"=>17, "city"=>"Kandy", "marks"=>72] |
| 3rd iteration | ["id"=>3, "name"=>"Sitha Kumari", "age"=>18, "city"=>"Galle", "marks"=>45] |
| 4th iteration | null — no more rows, while loop ends |
marks each time the page loads. This is a common real-world pattern: store raw data in MySQL, compute derived values in PHP.Grade Boundaries
| Marks | Grade | PHP Condition |
|---|---|---|
| 75 – 100 | A | $marks >= 75 |
| 65 – 74 | B | $marks >= 65 |
| 50 – 64 | C | $marks >= 50 |
| 0 – 49 | F | else |
10.21.6 – How All Files Connect
| File | Includes | SQL Used | Key PHP |
|---|---|---|---|
setup_db.php | nothing | CREATE DATABASE, CREATE TABLE | select_db(), query() |
connect.php | nothing | — | new mysqli(), connect_error, die() |
insert.php | require_once "connect.php" | INSERT INTO | $_POST, query(), insert_id |
retrieve.php | require_once "connect.php" | SELECT * FROM | num_rows, fetch_assoc() |
Request–Response Flow — insert.php
Browser Apache + PHP MySQL (school_db) | | | |-- GET /insert.php ---------->| | | | REQUEST_METHOD = "GET" | | | PHP block skipped | |<-- HTML form shown ----------| | | | | | (user fills and submits) | | | | | |-- POST /insert.php --------->| | | name=Kamal&age=18... |-- require_once connect.php->| open connection | |-- $_POST["name"] = "Kamal" | | |-- INSERT INTO students ---->| save new row | |<-- true, insert_id = 1 ----| |<-- "Student added! ID = 1" --|-- $conn->close() ---------->| close connection | + form shown again | |
Request–Response Flow — retrieve.php
Browser Apache + PHP MySQL (school_db) | | | |-- GET /retrieve.php -------->| | | |-- require_once connect.php->| open connection | |-- SELECT * FROM students -->| fetch all rows | |<-- result set (3 rows) -----| | |-- while fetch_assoc() | | | row 1: Kamal, 85, A | | | row 2: Nimal, 72, B | | | row 3: Sitha, 45, F | |<-- HTML table with all rows -|-- $conn->close() ---------->| close connection
How to Run the Activity — Step by Step
- Start Apache and MySQL in XAMPP Control Panel.
- Open
http://localhost/phpActivity/setup_db.php— confirm "Database ready" and "Table ready" messages appear. - Open
http://localhost/phpActivity/connect.php— confirm the page loads with no error message. - Open
http://localhost/phpActivity/insert.php— add at least 3 students with different marks. - Open
http://localhost/phpActivity/retrieve.php— verify all students appear in the table with correct grades.
http://localhost/... — never by double-clicking the file. Opening a .php file directly (e.g. from File Explorer) shows the raw PHP source code; it does not execute it.• Create =
INSERT INTO → check query() === TRUE, read insert_id
• Read =
SELECT * FROM → use num_rows, loop with fetch_assoc()
• Update =
UPDATE ... SET ... WHERE → always include WHERE or ALL rows are changed
• Delete =
DELETE FROM ... WHERE → always include WHERE or ALL rows are deleted
| Tag | Purpose | Type |
|---|---|---|
<html> | Root element | Structural |
<head> | Metadata section | Structural |
<body> | Visible content | Structural |
<title> | Browser tab title | Metadata |
<h1>–<h6> | Headings | Text |
<p> | Paragraph | Text |
<br> | Line break (self-closing) | Text |
<hr> | Horizontal rule | Text |
<b> | Bold | Formatting |
<i> | Italic | Formatting |
<u> | Underline | Formatting |
<strong> | Bold + semantic importance | Formatting |
<em> | Italic + semantic emphasis | Formatting |
<sub> | Subscript (H₂O) | Formatting |
<sup> | Superscript (x²) | Formatting |
<a> | Hyperlink | Link |
<img> | Image (self-closing) | Media |
<audio> | Audio player | Media |
<video> | Video player | Media |
<ul> | Unordered list (bullets) | List |
<ol> | Ordered list (numbered) | List |
<li> | List item | List |
<table> | Table | Table |
<tr> | Table row | Table |
<th> | Table header cell | Table |
<td> | Table data cell | Table |
<form> | Form container | Form |
<input> | Input field (text, radio, checkbox, submit...) | Form |
<textarea> | Multi-line text input | Form |
<select> | Dropdown list | Form |
<option> | Option in dropdown | Form |
<label> | Label for form element | Form |
<div> | Block container | Layout |
<span> | Inline container | Layout |
<marquee> | Scrolling text | Animation |
<style> | Internal CSS | CSS |
<link> | External CSS file | CSS |
PHP Quick Reference
| Concept | Syntax |
|---|---|
| PHP tags | <?php ... ?> |
| Output | echo "text"; |
| Variable | $name = "value"; |
| Concatenate | $a . $b |
| Array | $arr = ["a", "b"]; |
| Assoc array | $arr = ["key" => "val"]; |
| If-else | if($x>0){...}else{...} |
| For loop | for($i=0;$i<5;$i++){...} |
| While loop | while($i<5){...$i++;} |
| Foreach | foreach($arr as $k=>$v){...} |
| Function | function name($param){return $val;} |
| GET form data | $_GET["fieldname"] |
| POST form data | $_POST["fieldname"] |
| DB connect | new mysqli($host,$user,$pass,$db) |
| DB query | $conn->query($sql) |
| Fetch row | $result->fetch_assoc() |