10
Main Topics
80+
Sub-Topics
60+
Code Examples
2026
Exam Ready
10.1
Necessity of World Wide Web (WWW)

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.

The Internet is the physical network of computers. The WWW is a service that runs ON the Internet. They are not the same thing.
TermMeaning
WWWSystem of web pages linked together using hyperlinks and URLs
HTTPHyperText Transfer Protocol — the language used to transfer web pages
HTTPSSecure version of HTTP using SSL/TLS encryption
URLUniform Resource Locator — address of a web resource (e.g. https://www.google.com)
HyperlinkClickable text or image that connects to another web page or resource
Web BrowserSoftware used to access the WWW (e.g. Chrome, Firefox, Edge)
Web ServerA 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
Exam questions often ask you to "explain the necessity of the WWW" — list at least 5 uses with a brief explanation for each.

10.1.2 – Types of Web Sites

Websites can be broadly classified as Static or Dynamic.

TypeDescriptionTechnologyExample
StaticContent is fixed; same page shown to every userHTML, CSSPersonal portfolio, brochure site
DynamicContent changes based on user, time, or dataPHP, Python + DatabaseFacebook, 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-SideServer-Side
Where it runsBrowser (user's computer)Web server
LanguageJavaScript, HTML, CSSPHP, Python, ASP.NET
Database accessNo (directly)Yes
Source visible?YesNo
SpeedFast (no network needed)Depends on server/network
10.1
World Wide Web (WWW) හි අවශ්‍යතාව

10.1.1 – World Wide Web (WWW) යනු කුමක්ද?

World Wide Web (WWW) යනු Internet හරහා web browser භාවිතයෙන් ප්‍රවේශ වන, hypertext documents සහ multimedia content ඒකාබද්ධ කළ ක්‍රමවේදයකි. එය Tim Berners-Lee විසින් 1989 දී Switzerland හි CERN ආයතනයේදී නිර්මාණය කරන ලදී.

Internet යනු computers වල භෞතික ජාලයයි. WWW යනු Internet මත ක්‍රියාත්මක වන සේවාවකි. මේ දෙක එකිනෙකට වෙනස් දේවල් බව දත යුතුය.
Termඅර්ථය
WWWHyperlinks සහ URLs භාවිතයෙන් ඒකාබද්ධ web pages ක්‍රමවේදය
HTTPHyperText Transfer Protocol — web pages හුවමාරු කිරීමේ භාෂාව
HTTPSSSL/TLS encryption භාවිතා කළ HTTP හි ආරක්ෂිත අනුවාදය
URLUniform Resource Locator — web resource හි ලිපිනය (උදා: https://www.google.com)
Hyperlinkවෙනත් web page හෝ resource වෙත සම්බන්ධ වන click කළ හැකි text හෝ image
Web BrowserWWW ප්‍රවේශ කිරීමට භාවිතා කරන software (උදා: Chrome, Firefox, Edge)
Web ServerInternet හරහා web pages host කර serve කරන computer

WWW හි අවශ්‍යතාව (ඇයි WWW අවශ්‍ය?):

  • ඉතා අඩු වියදමින් ලොව පුරා තොරතුරු බෙදාගැනීම
  • E-commerce (online ගෙනීම, banking)
  • E-learning සහ online අධ්‍යාපනය
  • සන්නිවේදනය (email, social media, video calls)
  • විනෝදාංශ (streaming, games)
  • රජය සහ රාජ්‍ය සේවා
විභාගයේ "WWW හි අවශ්‍යතාව පැහැදිලි කරන්න" ලෙස ප්‍රශ්න ලැබේ — සෑම කරුණකටම කෙටි විස්තරයක් සමඟ අවම කරුණු 5ක් ලියන්න.

10.1.2 – Website වර්ග

Websites ප්‍රධාන ලෙස Static හෝ Dynamic ලෙස වර්ග කළ හැකිය.

වර්ගයවිස්තරයTechnologyඋදාහරණ
StaticContent ස්ථිරයි; සෑම user කෙනෙකුටම එකම page පෙනේHTML, CSSපුද්ගලික portfolio, brochure site
DynamicUser, වේලාව හෝ data අනුව content වෙනස් වේPHP, Python + DatabaseFacebook, 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-SideServer-Side
ක්‍රියාත්මක වන තැනBrowser (user ගේ computer)Web server
භාෂාවJavaScript, HTML, CSSPHP, Python, ASP.NET
Database accessනෑ (සෘජුව)ඔව්
Source code දෘශ්‍යද?ඔව්නෑ
වේගයඉක්මන් (network අවශ්‍ය නෑ)Server/network මත රඳා පවතී
10.2
Analysis of User Requirements

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.

HTML – Navigation Menu
<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
පරිශීලක අවශ්‍යතා විශ්ලේෂණය

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 ඇතුළත් කරයි.

HTML – Navigation Menu
<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
Introduction to HTML

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 .html or .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)
HTML – Tag Structure
<!-- 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">

AttributeUsed withPurpose
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
styleMost tagsInline CSS styling
idMost tagsUnique identifier
classMost tagsCSS class name
nameForm elementsName 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.

HTML Element Structure
<h1>Welcome to My Website</h1>
│        │                    │
Open Tag  Content         Close Tag

10.3.5 – Building Blocks of a Web Page

HTML – Basic Page Structure
<!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

HTML – Complete First 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
Remember: <!DOCTYPE html> declares the document type. Without it, the browser may render in "quirks mode".
10.3
HTML හැඳින්වීම

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 (ඒකක ඇතුළේ ඒකක) ලෙස ලිවිය හැකිය
HTML – Tag ව්‍යූහය
<!-- 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">

AttributeTagsඅරමුණ
href<a>Link destination නිශ්චිත කරයි
src<img>Image file path නිශ්චිත කරයි
alt<img>Image සඳහා විකල්ප text
width, height<img>, <table>Dimensions set කරයි
styleබොහෝ tagsInline CSS styling
idබොහෝ tagsඅනන්‍ය හඳුනාගැනීමේ ලකුණ
classබොහෝ tagsCSS class නාමය
nameForm elementsForm 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.

HTML Element ව්‍යූහය
<h1>Welcome to My Website</h1>
│        │                    │
Open Tag  Content         Close Tag

10.3.5 – Web Page හි ගොඩනැගීමේ ආකෘතිය

HTML – මූලික 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 නිර්මාණය කරමු

HTML – සම්පූර්ණ පළමු 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
Basic HTML Tags

10.4.1 – <p> — Paragraph

The <p> tag defines a paragraph. Browsers automatically add space before and after paragraphs.

HTML
<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.

HTML
<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.

HTML
<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).

HTML
<font size="5">Large text</font>
<font size="2">Small text</font>
<!-- Modern equivalent with CSS: -->
<p style="font-size: 24px;">Large text</p>
The <font> tag is deprecated in HTML5. Use CSS font-size property instead.

10.4.5 – <b> — Bold

HTML
<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

HTML
<i>This text is italic.</i>
<!-- Also: <em> for semantically emphasised text -->
<em>This is emphasised text.</em>

10.4.7 – <u> — Underline

HTML
<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).

HTML
<p>Do <strong>NOT</strong> press this button!</p>

10.4.9 – Alignment — align Attribute

HTML
<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

HTML
<p>H<sub>2</sub>O (Water)</p>
<p>CO<sub>2</sub> (Carbon Dioxide)</p>

10.4.11 – <sup> — Superscript

HTML
<p>E = mc<sup>2</sup></p>
<p>5<sup>th</sup> August</p>

10.4.12 – <font face> — Font Family

HTML
<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:

MethodExampleDescription
Named coloursred, blue, greenPredefined colour names (140 standard names)
Hex code#FF0000Hexadecimal RGB (most common)
RGB valuergb(255, 0, 0)Red, Green, Blue values (0–255)
HTML – Font Colour
<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

HTML
<!-- Entire page background -->
<body bgcolor="#FFFF00">   <!-- Yellow background -->

<!-- Background for a section (CSS): -->
<p style="background-color: lightblue;">Blue background</p>
Know how to specify colours using all 3 methods (named, hex, rgb). Understand that #RRGGBB — first 2 digits = Red, middle 2 = Green, last 2 = Blue. #FF0000 = pure red, #00FF00 = pure green, #0000FF = pure blue.
10.4
මූලික HTML Tags

10.4.1 – <p> — Paragraph

<p> tag paragraph නිර්වචනය කරයි. Browser ස්වයංක්‍රීයව paragraphs ඉදිරිපිට සහ පසුපිට space add කරයි.

HTML
<p>මෙය paragraph එකකි.</p>
<p>මෙය තවත් paragraph එකකි.</p>

10.4.2 – <br> — Line Break

<br> tag single line break insert කරයි. Self-closing (void) tag — closing tag අවශ්‍ය නොවේ.

HTML
<p>Line one.<br>Line two.<br>Line three.</p>

10.4.3 – <H1> සිට <H6> — Headings

HTML හි headings 6ක් ඇත. <h1> ලොකුම සහ වැදගත්ම; <h6> කුඩාම ය.

HTML
<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).

HTML
<font size="5">Large text</font>
<font size="2">Small text</font>
<!-- CSS හරහා නවීන ක්‍රමය: -->
<p style="font-size: 24px;">Large text</p>
<font> tag HTML5 හි deprecated වී ඇත. ඒ වෙනුවට CSS font-size property භාවිතා කරන්න.

10.4.5 – <b> — Bold

HTML
<b>මෙය bold text.</b>
<!-- සේමෝ: <strong> — semantically වැදගත් bold text -->
<strong>මෙය වැදගත් bold text.</strong>

10.4.6 – <i> — Italic

HTML
<i>මෙය italic text.</i>
<!-- සේමෝ: <em> — semantically emphasized text -->
<em>මෙය emphasized text.</em>

10.4.7 – <u> — Underline

HTML
<u>මෙය underlined text.</u>

10.4.8 – <strong> — Strong Importance

<strong> text ඉතා වැදගත් ලෙස සලකුණු කරයි. දෘශ්‍යමාන bold AND semantically වැදගත් (screen readers සහ search engines ද හඳුනාගනී).

HTML
<p>DO <strong>NOT</strong> press this button!</p>

10.4.9 – Alignment — align Attribute

HTML
<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

HTML
<p>H<sub>2</sub>O (Water)</p>
<p>CO<sub>2</sub> (Carbon Dioxide)</p>

10.4.11 – <sup> — Superscript

HTML
<p>E = mc<sup>2</sup></p>
<p>5<sup>th</sup> August</p>

10.4.12 – <font face> — Font Family

HTML
<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 coloursred, blue, greenපූර්ව-නිර්වචිත වර්ණ නාම (සම්මත නාම 140)
Hex code#FF0000Hexadecimal RGB (වඩාත් සාමාන්‍ය)
RGB valuergb(255, 0, 0)Red, Green, Blue values (0–255)
HTML – Font Colour
<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 යෙදීම

HTML
<!-- සම්පූර්ණ page background -->
<body bgcolor="#FFFF00">   <!-- Yellow background -->

<!-- Section background (CSS): -->
<p style="background-color: lightblue;">Blue background</p>
වර්ණ සඳහා ක්‍රම 3 (named, hex, rgb) දැනගත යුතුය. #RRGGBB — මුල් digits 2 = Red, මැද 2 = Green, අන්ත 2 = Blue. #FF0000 = pure red, #00FF00 = pure green, #0000FF = pure blue.
10.5
Uses of HTML to Create Linked Web Pages

10.5.1–10.5.3 – Content, Home Page & Linked Pages

Websites consist of multiple linked pages. The anchor tag <a> creates hyperlinks.

HTML – 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.

HTML
<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>.

HTML
<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>.

HTML
<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.

HTML
<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 TypeExampleMeaning
Same foldersrc="image.jpg"Image is in the same folder as HTML file
Subfoldersrc="images/photo.jpg"Image is inside an "images" subfolder
Parent foldersrc="../image.jpg"Image is one folder up
Absolute URLsrc="https://example.com/img.jpg"Image from the internet

10.5.7 – HTML Tables

TagMeaning
<table>Defines the table
<tr>Table Row
<th>Table Header cell (bold + centered by default)
<td>Table Data cell
<caption>Table caption/title
HTML – Complete Table
<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

HTML
<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

HTML
<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

HTML
<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.

HTML – Rowspan & Colspan
<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>
Rowspan and colspan are very common exam questions. Practice drawing the table on paper first, then writing the HTML.

10.5.8 – Animation using <marquee>

The <marquee> tag creates scrolling/moving text.

HTML
<!-- 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
<!-- 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
<!-- 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 -->
AttributeEffect
controlsShows play/pause/volume controls
autoplayStarts playing automatically
loopRepeats the media continuously
mutedStarts with no sound
posterImage 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.

HTML
<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>
HTML5 introduced semantic tags like <header>, <nav>, <main>, <footer>, <section>, <article> which are more meaningful than <div>.
10.5
Linked Web Pages නිර්මාණය සඳහා HTML භාවිතය

10.5.1–10.5.3 – Content, Home Page සහ Linked Pages

Websites linked pages කිහිපයකින් සමන්විත වේ. Anchor tag <a> hyperlinks නිර්මාණය කරයි.

HTML – 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" භාවිතා කරන්න.

HTML
<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>.

HTML
<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>.

HTML
<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 ය.

HTML
<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 වර්ගයඋදාහරණඅර්ථය
එකම foldersrc="image.jpg"Image, HTML file සමඟ එකම folder හි ඇත
Subfoldersrc="images/photo.jpg"Image "images" subfolder ඇතුළේ ඇත
Parent foldersrc="../image.jpg"Image ඉහළ folder හි ඇත
Absolute URLsrc="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
HTML – සම්පූර්ණ Table
<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

HTML
<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 කිරීම

HTML
<table background="bg.jpg" width="100%">
  <tr><td>Image background සහිත Content</td></tr>
</table>

10.5.7.6 – Table හි සම්පූර්ණ Width Set කිරීම

HTML
<table width="600">   <!-- Fixed pixel width -->
<table width="80%">    <!-- Page width හි percentage -->

10.5.7.7 – Rowspan සහ Colspan

මෙම attributes rows හෝ columns හරහා cells merge (ඒකාබද්ධ) කරයි.

HTML – Rowspan & Colspan
<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>
Rowspan සහ colspan විභාගයේ ඉතා සාමාන්‍ය ප්‍රශ්නය. HTML ලිවීමට පෙර paper හි table draw කිරීම ප්‍රයෝජනවත්ය.

10.5.8 – <marquee> Animation

<marquee> tag scrolling/moving text නිර්මාණය කරයි.

HTML
<!-- 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
<!-- 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
<!-- 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ක්‍රියාව
controlsPlay/pause/volume controls පෙන්වයි
autoplayස්වයංක්‍රීයව play ආරම්භ කරයි
loopMedia නිරන්තරව repeat කරයි
mutedSound නොමැතිව ආරම්භ කරයි
posterVideo load වීමට පෙර image (video only)

10.5.10 – <div> — Division / Section

<div> tag HTML elements group කිරීමේ block-level container (division) නිර්වචනය කරයි. තනිව visual effect නොමැත — CSS layout සඳහා භාවිතා කෙරේ.

HTML
<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>
HTML5 හි semantic tags ඇත: <header>, <nav>, <main>, <footer>, <section>, <article> — <div> ට වඩා අর্থවත් ය.
10.6
Working with HTML Forms

HTML forms collect input from the user and send it to a server for processing.

10.6.1.1 – <form> Tag

HTML – Form Structure
<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) -->
AttributeValueDescription
actionURLScript that processes the form
methodget / postHow data is sent to server
enctypemultipart/form-dataRequired for file uploads

10.6.1.2 – Text Input Field

HTML
<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

HTML
<label for="pwd">Password:</label>
<input type="password" id="pwd" name="password">
<!-- Characters are hidden (shown as ****) -->

10.6.1.4 – Text Area

HTML
<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)

HTML
<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

HTML
<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

HTML
<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

HTML
<input type="submit" value="Submit Form">
<!-- Or using <button> tag: -->
<button type="submit">Submit</button>

10.6.1.9 – Reset Button

HTML
<input type="reset" value="Clear Form">
<!-- Clears all form inputs back to default values -->
HTML – Complete Registration Form Example
<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>
Difference between radio buttons and checkboxes: Radio = ONLY ONE can be selected (same name groups them). Checkbox = MULTIPLE can be selected.
10.6
HTML Forms සමඟ වැඩ කිරීම

HTML forms user ගෙන් input සගන්වා server වෙත processing සඳහා යවයි.

10.6.1.1 – <form> Tag

HTML – Form ව්‍යූහය
<form action="process.php" method="post">
  <!-- Form elements මෙහි ඇතුළත් කරන්න -->
</form>

<!-- action = form data යවන URL -->
<!-- method = get (URL හි දිස්වේ) හෝ post (සැඟවී, ආරක්ෂිත) -->
AttributeValueවිස්තරය
actionURLForm process කරන script
methodget / postData server වෙත යවන ක්‍රමය
enctypemultipart/form-dataFile uploads සඳහා අවශ්‍ය

10.6.1.2 – Text Input Field

HTML
<label for="fname">First Name:</label>
<input type="text"
       id="fname"
       name="firstname"
       placeholder="ඔබේ නම ඇතුළු කරන්න"
       maxlength="50"
       size="30">

10.6.1.3 – Password Input

HTML
<label for="pwd">Password:</label>
<input type="password" id="pwd" name="password">
<!-- Characters සැඟවී ඇත (****ලෙස පෙනේ) -->

10.6.1.4 – Text Area

HTML
<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)

HTML
<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

HTML
<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

HTML
<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

HTML
<input type="submit" value="Form Submit කරන්න">
<!-- හෝ <button> tag: -->
<button type="submit">Submit</button>

10.6.1.9 – Reset Button

HTML
<input type="reset" value="Form Clear කරන්න">
<!-- Form inputs default values වෙත clear කරයි -->
HTML – සම්පූර්ණ Registration Form
<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>
Radio buttons සහ checkboxes අතර වෙනස: Radio = එකක් පමණ select කළ හැකිය (එකම name group කරයි). Checkbox = කිහිපයක් select කළ හැකිය.
10.7
How to View Websites?

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 EngineURL
Googlewww.google.com
Bingwww.bing.com
Yahoowww.yahoo.com
DuckDuckGowww.duckduckgo.com

How search engines work:

  1. Crawling — robots (spiders) browse the web and collect web pages
  2. Indexing — web pages are stored and organised in a database
  3. Ranking — when you search, results are ranked by relevance
  4. Displaying results — SERP (Search Engine Results Page) is shown
10.7
Websites බලන ආකාරය

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 EngineURL
Googlewww.google.com
Bingwww.bing.com
Yahoowww.yahoo.com
DuckDuckGowww.duckduckgo.com

Search engines ක්‍රියා කරන ආකාරය:

  1. Crawling — robots (spiders) web browse කර pages collect කරයි
  2. Indexing — pages database හි ගබඩා කර සංවිධානය කරයි
  3. Ranking — search කළ විට relevance අනුව ප්‍රතිඵල rank කරයි
  4. Displaying results — SERP (Search Engine Results Page) දර්ශනය කරයි
10.8 – 10.12
Cascading Style Sheets (CSS)

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

CSS – Basic 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.

HTML
<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.

HTML
<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.

HTML – Link to External CSS
<head>
  <link rel="stylesheet" href="style.css">
</head>
CSS – style.css file
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!

MethodWhere WrittenPriorityBest For
InlineInside HTML tagHighestOne-off styles
Internal<style> in <head>MediumSingle page
ExternalSeparate .css fileLowestMultiple pages (BEST)
The cascading order (priority): Inline CSS > Internal CSS > External CSS. When two rules conflict, the one with higher priority wins.
10.8 – 10.12
Cascading Style Sheets (CSS)

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

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 කෙරේ.

HTML
<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 ලිවිය හැකිය.

HTML
<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 කෙරේ.

HTML – External CSS Link
<head>
  <link rel="stylesheet" href="style.css">
</head>
CSS – style.css file
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හොඳම
InlineHTML tag ඇතුළේඉහළමOne-off styles
Internal<style> in <head>මධ්‍යSingle page
Externalවෙනම .css fileඅඩුමPages කිහිපයකට (BEST)
Cascading order (priority): Inline CSS > Internal CSS > External CSS. Rules දෙකක් conflict වූ විට, වැඩි priority ඇති ජය ගනී.
10.10
Types of CSS Selectors

10.10.1 – Element Selector

Selects ALL elements of a specific HTML tag.

CSS
/* 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).

CSS
/* 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 + HTML
/* 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 + HTML
/* 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.

CSS
/* Applies to every element */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
SelectorSyntaxExampleTargets
Elementtagp { }All <p> elements
Class.classname.red { }All elements with class="red"
ID#idname#main { }Element with id="main"
Universal** { }All elements
Groupa, b, ch1, h2 { }All listed elements
10.10
CSS Selectors වර්ග

10.10.1 – Element Selector

Specific HTML tag හි සියලු elements select කරයි.

CSS
/* සියලු <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 කරයි.

CSS
/* 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 + HTML
/* 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 + HTML
/* 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 කරයි.

CSS
/* සෑම element එකකටම apply වේ */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
SelectorSyntaxඋදාහරණTarget
Elementtagp { }සියලු <p> elements
Class.classname.red { }class="red" ඇති elements
ID#idname#main { }id="main_si" ඇති element
Universal** { }සියලු elements
Groupa, b, ch1, h2 { }Listed elements සියල්ල
10.11
CSS Commands (Properties)
CSS – All Key Properties with Examples
/* 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

CSS
/* This is a single line CSS comment */

/*
  This is a
  multi-line CSS comment
*/

10.12.1 – CSS for Tables

CSS
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

CSS
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
CSS Commands (Properties)
CSS – ප්‍රධාන Properties සියල්ල
/* 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
/* CSS comments මෙලෙස ලිවිය යුතුය */
/* Comment කිහිපු lines හරහා විය හැකිය
   HTML comments (<!-- -->) CSS හි ක්‍රියා නොකරයි */
10.13
Web Authoring Tools

Web authoring tools help create web pages without manually writing all the code.

ToolTypeDescription
Notepad / Notepad++Text EditorFree, simple; you write all HTML code manually
VS CodeCode EditorFree, powerful with syntax highlighting and plugins
Sublime TextCode EditorFast and lightweight code editor
Adobe DreamweaverWYSIWYGPaid; visual design + code view; professional tool
WordPressCMSContent Management System; no coding needed
Wix / SquarespaceWebsite BuilderDrag-and-drop; hosted online

WYSIWYG = What You See Is What You Get — the design view matches the final output.

10.13
Web Authoring Tools
Toolවර්ගයවිශේෂතා
NotepadText EditorWindows built-in, සරල, HTML/CSS/PHP manual ලිවීමට
VS CodeCode EditorFree, powerful, extensions, syntax highlighting
Sublime TextCode Editorලෙහෙසි, ඉක්මන්, multiple cursor editing
DreamweaverWYSIWYG + CodeAdobe; visual design + code view දෙකම
WordPressCMSCoding නොමැතිව dynamic websites; themes, plugins
WixOnline BuilderDrag-and-drop, beginners සඳහා, hosting included

WYSIWYG = What You See Is What You Get — design view, final output සිදු ස..

10.14 – 10.15
Creating Dynamic Web Pages Using PHP and MySQL

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

Process Flow
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
PHP requires a web server (Apache/Nginx) and PHP installed. For local development, use XAMPP or WAMP (free software packages that include Apache + MySQL + PHP).

10.15.5 – Embedding PHP Code in a Web Page

PHP in HTML
<!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
<?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
<?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 – Variables
<?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
<?php
$a = 10;
$b = -5;
$c = 1000;
echo $a + $b;  // 5
var_dump($a);  // int(10)
?>

10.15.9.2 – Double (Float)

PHP
<?php
$price  = 9.99;
$weight = 3.14159;
echo $price;      // 9.99
var_dump($price); // float(9.99)
?>

10.15.9.3 – Boolean

PHP
<?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
<?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
<?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
<?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
<?php
function counter() {
  static $count = 0;  // only initialised once
  $count++;
  echo $count . " ";
}
counter();  // 1
counter();  // 2
counter();  // 3
?>
10.14 – 10.15
PHP සහ MySQL භාවිතා කර Dynamic Web Pages නිර්මාණය

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 ක්‍රියා කරන ආකාරය

Process Flow
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 කරයි
PHP ට web server (Apache/Nginx) සහ PHP install කළ යුතුය. Local development සඳහා XAMPP හෝ WAMP (Apache + MySQL + PHP ඇතුළත් free package) භාවිතා කරන්න.

10.15.5 – Web Page හි PHP Code Embed කිරීම

PHP in HTML
<!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
<?php
// Single-line comment
# Single-line comment (වෙනත් ස්වරූපය)
echo "Hello";  // inline comment
?>

10.15.7.2 – Multi-line Comments

PHP
<?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 – Variables
<?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
<?php
$a = 10;
$b = -5;
$c = 1000;
echo $a + $b;  // 5
var_dump($a);  // int(10)
?>

10.15.9.2 – Double / Float (දශමාංශ සංඛ්‍යා)

PHP
<?php
$price  = 9.99;
$weight = 3.14159;
echo $price;      // 9.99
var_dump($price); // float(9.99)
?>

10.15.9.3 – Boolean (සත්‍ය/අසත්‍ය)

PHP
<?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
<?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
<?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
<?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
<?php
function counter() {
  static $count = 0;  // එක් වරක් පමණ initialise
  $count++;
  echo $count . " ";
}
counter();  // 1
counter();  // 2
counter();  // 3
?>
10.16
PHP Arrays

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
<?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
<?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
<?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
?>
10.16
PHP Arrays

Array එකක් variable එකක multiple values ගබඩා කරයි. ලැයිස්තුවක් ලෙස සිතන්න.

10.16.1.1 – Numeric (Indexed) Array

Elements 0 සිට ආරම්භ වන numeric index මගින් access කෙරේ.

PHP
<?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
<?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
<?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
Control Structures

10.17.1 – PHP Selection Statements

10.17.1.1 – If Statement

PHP
<?php
$age = 18;

if ($age >= 18) {
  echo "You are an adult.";
}
?>

10.17.1.2 – If...Else Statement

PHP
<?php
$marks = 55;

if ($marks >= 50) {
  echo "Pass";
} else {
  echo "Fail";
}
?>

10.17.1.3 – If...Elseif...Else

PHP
<?php
$marks = 72;

if ($marks >= 75) {
  echo "Distinction";
} elseif ($marks >= 65) {
  echo "Merit";
} elseif ($marks >= 50) {
  echo "Pass";
} else {
  echo "Fail";
}
?>
PHP Comparison Operators: == (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
<?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
<?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
<?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>";
}
?>
LoopWhen to useCondition check
whileUnknown number of repetitionsBefore body (may not run at all)
do...whileMust run at least onceAfter body
forKnown number of repetitionsBefore body
foreachIterate arraysAutomatic
10.17
Control Structures

10.17.1 – Selection Control Structures

10.17.1.1 – If Statement

Condition එකක් true නම් පමණක් code execute කරයි.

PHP
<?php
$age = 18;

if ($age >= 18) {
  echo "ඔබ වැඩිහිටියෙකි.";
}
?>

10.17.1.2 – If...Else Statement

PHP
<?php
$marks = 55;

if ($marks >= 50) {
  echo "Pass";
} else {
  echo "Fail";
}
?>

10.17.1.3 – If...Elseif...Else

PHP
<?php
$marks = 72;

if ($marks >= 75) {
  echo "Distinction";
} elseif ($marks >= 65) {
  echo "Merit";
} elseif ($marks >= 50) {
  echo "Pass";
} else {
  echo "Fail";
}
?>
PHP Comparison Operators: == (සමාන), != (සමාන නෙමෙ), > (වැඩි), < (අඩු), >= (වැඩි හෝ සමාන), <= (අඩු හෝ සමාන), === (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
<?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
<?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
<?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
whileRepetitions ගණන නොදන්නා විටBody ට පෙර (ශූන්‍ය වාරයක් ද ක්‍රියා නොකිරීමට ඉඩ ඇත)
do...whileඅවම වශයෙන් එක් වරක් ක්‍රියා කළ යුතු විටBody ට පසු
forRepetitions ගණන දන්නා විටBody ට පෙර
foreachArrays iterate කිරීමටස්වයංක්‍රීය
10.18
Introduction to foreach in PHP

The foreach loop is designed specifically for iterating over arrays. It automatically goes through each element.

PHP – Foreach Loops
<?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>";
?>
10.18
PHP හි foreach හැඳින්වීම

foreach loop arrays iterate කිරීමට විශේෂිතව නිර්මාණය කෙරේ. ස්වයංක්‍රීයව සෑම element හරහා යාවිසේ.

PHP – Foreach Loops
<?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>";
?>
10.19
PHP Functions

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
<?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
<?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
?>
10.19
PHP Functions

Function එකක් specific task එකක් ඉටු කරන reusable code block. එක් වරක් define කර කිහිප වරක් call කළ හැකිය.

10.19.1 – User Defined Functions

PHP
<?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
<?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
?>
10.20
Database Connectivity (PHP + MySQL)

MySQL is the most popular Relational Database Management System (RDBMS) used with PHP. Data is stored in tables (rows and columns).

For local development: Install XAMPP. It includes Apache (web server), MySQL (database), and PHP. Access phpMyAdmin at http://localhost/phpmyadmin

10.20.1 – Create MySQL Database

SQL – Create Database
-- Using phpMyAdmin SQL tab, or MySQL command line:
CREATE DATABASE school_db;
USE school_db;

10.20.2 – Create the Table

SQL – Create 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
<?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 – Insert Data
<?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

PHP – HTML Form + Database Insert
<!-- 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 – Retrieve Data from Database
<?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

SQL – Essential Commands
-- 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;
Know ALL 4 CRUD operations:
• 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

PHP – Full 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>
10.20
Database Connectivity (PHP + MySQL)

MySQL PHP සමඟ භාවිතා කරන ජනප්‍රිය Relational Database Management System (RDBMS). Data tables (rows සහ columns) හි ගබඩා කෙරේ.

Local development: XAMPP install කරන්න. Apache (web server), MySQL (database), සහ PHP ඇතුළත් ය. phpMyAdmin: http://localhost/phpmyadmin

10.20.1 – MySQL Database නිර්මාණය

SQL – Database නිර්මාණය
-- phpMyAdmin SQL tab හෝ MySQL command line:
CREATE DATABASE school_db;
USE school_db;

10.20.2 – Table නිර්මාණය

SQL – 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 – Database Connection
<?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 – Data Insert කිරීම
<?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 – Data Retrieve කිරීම
<?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

OperationSQL Commandවිස්තරය
CreateINSERT INTOනව record add
ReadSELECTRecords retrieve
UpdateUPDATERecords update
DeleteDELETERecords delete
SQL – ප්‍රයෝජනවත් Commands
-- 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;
UPDATE/DELETE commands හි WHERE clause අමතක නොකරන්න! WHERE නොමැතිව සියලු records update/delete වේ. මෙය විභාගයේ ඉතා වැදගත්.
10.21
Practical Activity — Student Registration System

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.

Before starting: open XAMPP Control Panel and start both Apache and MySQL. All files must be saved inside 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

FilePurposeMain SQL / PHP Concept
setup_db.phpCreate database and tableCREATE DATABASE, CREATE TABLE
connect.phpReusable connection filenew mysqli(), require_once
insert.phpHTML form + save to database$_POST, INSERT INTO
retrieve.phpDisplay all studentsSELECT *, fetch_assoc()

Database Structure — school_db → students table

ColumnData TypeDescription
idINT AUTO_INCREMENT PRIMARY KEYUnique row number — set automatically, never entered manually
nameVARCHAR(100) NOT NULLStudent name — text up to 100 characters, required
ageINTStudent age — whole number
cityVARCHAR(50)City or town — text up to 50 characters
marksFLOATExam marks — decimal number (e.g. 85.5)
MySQL Data Types you must know: 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 – 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

CodeExplanation
new mysqli("localhost","root","")Connects to MySQL with only 3 arguments — no database name, because it does not exist yet
$conn->connect_errorContains 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 EXISTSCreates 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 EXISTSCreates the table only if it does not already exist
INT AUTO_INCREMENT PRIMARY KEYThe id column increases automatically — MySQL assigns it; you never insert it manually
VARCHAR(100) NOT NULLText field, max 100 characters — NOT NULL means this column cannot be left empty
SELECT COUNT(*) AS totalCounts 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 – 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

ParameterValue (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 – require_once
<?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 $_POST data and saves it to MySQL.
  • Part B (HTML below) — the form the user fills in; always displayed.

Page Flow

EventREQUEST_METHODWhat PHP does
User opens insert.php for the first timeGETPHP 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 dataPOSTPHP block runs → data saved → success message shown → form shown again

Full Script — insert.php

PHP + HTML – 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

CodeExplanation
$_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) === TRUEINSERT returns true on success (not a result set) — use === for strict comparison
$conn->insert_idThe AUTO_INCREMENT id MySQL assigned to the newly inserted row
$conn->errorContains the MySQL error message if the last query failed

Key HTML Form Attributes in insert.php

AttributeValueExplanation
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 textBecomes 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
In the INSERT statement, text values (name, city) must be wrapped in single quotes: '$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 + HTML – 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

CodeExplanation
$conn->query($sql)For SELECT, this returns a result set object — not just true/false like INSERT
$result->num_rowsThe 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 DESCSorts 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 iterationnull — no more rows, while loop ends
The grade (A, B, C, F) is not stored in the database — it is calculated from 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

MarksGradePHP Condition
75 – 100A$marks >= 75
65 – 74B$marks >= 65
50 – 64C$marks >= 50
0 – 49Felse

10.21.6 – How All Files Connect

FileIncludesSQL UsedKey PHP
setup_db.phpnothingCREATE DATABASE, CREATE TABLEselect_db(), query()
connect.phpnothing—new mysqli(), connect_error, die()
insert.phprequire_once "connect.php"INSERT INTO$_POST, query(), insert_id
retrieve.phprequire_once "connect.php"SELECT * FROMnum_rows, fetch_assoc()

Request–Response Flow — insert.php

Flow Diagram
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

Flow Diagram
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

  1. Start Apache and MySQL in XAMPP Control Panel.
  2. Open http://localhost/phpActivity/setup_db.php — confirm "Database ready" and "Table ready" messages appear.
  3. Open http://localhost/phpActivity/connect.php — confirm the page loads with no error message.
  4. Open http://localhost/phpActivity/insert.php — add at least 3 students with different marks.
  5. Open http://localhost/phpActivity/retrieve.php — verify all students appear in the table with correct grades.
PHP files must be opened via 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.
Know ALL 4 CRUD operations and which PHP functions they use:
• 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
QUICK REFERENCE
Exam Cheat Sheet — All Key HTML Tags
TagPurposeType
<html>Root elementStructural
<head>Metadata sectionStructural
<body>Visible contentStructural
<title>Browser tab titleMetadata
<h1>–<h6>HeadingsText
<p>ParagraphText
<br>Line break (self-closing)Text
<hr>Horizontal ruleText
<b>BoldFormatting
<i>ItalicFormatting
<u>UnderlineFormatting
<strong>Bold + semantic importanceFormatting
<em>Italic + semantic emphasisFormatting
<sub>Subscript (H₂O)Formatting
<sup>Superscript (x²)Formatting
<a>HyperlinkLink
<img>Image (self-closing)Media
<audio>Audio playerMedia
<video>Video playerMedia
<ul>Unordered list (bullets)List
<ol>Ordered list (numbered)List
<li>List itemList
<table>TableTable
<tr>Table rowTable
<th>Table header cellTable
<td>Table data cellTable
<form>Form containerForm
<input>Input field (text, radio, checkbox, submit...)Form
<textarea>Multi-line text inputForm
<select>Dropdown listForm
<option>Option in dropdownForm
<label>Label for form elementForm
<div>Block containerLayout
<span>Inline containerLayout
<marquee>Scrolling textAnimation
<style>Internal CSSCSS
<link>External CSS fileCSS

PHP Quick Reference

ConceptSyntax
PHP tags<?php ... ?>
Outputecho "text";
Variable$name = "value";
Concatenate$a . $b
Array$arr = ["a", "b"];
Assoc array$arr = ["key" => "val"];
If-elseif($x>0){...}else{...}
For loopfor($i=0;$i<5;$i++){...}
While loopwhile($i<5){...$i++;}
Foreachforeach($arr as $k=>$v){...}
Functionfunction name($param){return $val;}
GET form data$_GET["fieldname"]
POST form data$_POST["fieldname"]
DB connectnew mysqli($host,$user,$pass,$db)
DB query$conn->query($sql)
Fetch row$result->fetch_assoc()