UNIT 1: Foundations of the Web
I. Foundations of the Web
Internet vs. World Wide Web (WWW)
-
Internet: A global network of networks connecting millions of computers using standardized protocols (like TCP/IP). It is the underlying infrastructure.
-
World Wide Web (WWW): An information-sharing model built on top of the Internet. It uses HTTP to transmit HTML documents accessed via URLs using web browsers.
-
Relationship: The Internet is the highway system; the Web is a specific service (like mail or video streaming) that runs on it. The Web cannot exist without the Internet, but the Internet can exist without the Web.
[!TIP] Common Exam Question: "Differentiate between Internet and WWW." Focus on: Infrastructure vs. Service, Protocols used (TCP/IP vs. HTTP/HTML), and Dependency.
Web Browsers and Web Servers
-
Web Browser (Client): Software application (Chrome, Firefox) that requests, receives, interprets, and displays web content (HTML, CSS, JS). It renders the user interface.
-
Web Server: Software/hardware (Apache, Nginx, IIS) that stores, processes, and delivers web pages to clients upon request. It listens for HTTP requests and sends HTTP responses.
-
Request-Response Cycle:
-
User enters URL → Browser sends HTTP Request to server.
-
Server processes request, locates resource, sends HTTP Response (status code, headers, body).
-
Browser receives response, renders content (HTML/CSS/JS) for the user.
-
Hypertext Transfer Protocol (HTTP)
-
Purpose: The application-layer protocol governing the exchange of hypermedia (HTML documents) between browsers (clients) and servers. It is stateless (each request is independent).
-
Structure of HTTP Request:
GET /index.html HTTP/1.1 Host: www.example.com [Other headers]-
Request Line: Method, Request-URI, HTTP Version.
-
Headers: Key-value pairs (Host, User-Agent, Accept).
-
Body: Optional data (e.g., for POST).
-
-
Structure of HTTP Response:
HTTP/1.1 200 OK Content-Type: text/html [Other headers] [Blank line] <html>...</html> (Response Body)-
Status Line: HTTP Version, Status Code (200, 404, 500), Reason Phrase.
-
Headers: Key-value pairs (Content-Type, Content-Length).
-
Body: The requested resource (HTML, image, etc.).
-
-
Common HTTP Methods:
| Method | Purpose | Idempotent? | Has Body? | | :--- | :--- | :--- | :--- | | GET | Retrieve data (safe, no side-effects) | Yes | No | | POST | Submit data (create/update, side-effects) | No | Yes | | PUT | Replace a resource | Yes | Yes | | DELETE | Remove a resource | Yes | No |
Web Publishing Process
-
Planning: Define purpose, audience, sitemap.
-
Design: Create wireframes/mockups (UI/UX).
-
Development: Write code (HTML, CSS, JS, server-side).
-
Testing: Cross-browser, functionality, performance.
-
Deployment: Upload files to a web server via FTP/hosting control panel.
-
Maintenance: Update content, fix issues, monitor traffic.
- Tools: Text editors (VS Code), IDEs, version control (Git), FTP clients (FileZilla), browser dev tools.
UNIT 1: Web Design and User Experience
II. Web Design and User Experience
Web Design Issues
-
Browser Compatibility: Different browsers (Chrome, Firefox, Safari, Edge) may render HTML/CSS/JS differently. Use standard-compliant code, CSS resets, and cross-browser testing.
-
Bandwidth Limitations: Slow connections lead to poor user experience. Optimize by:
-
Minifying CSS/JS files.
-
Compressing images (use correct formats: JPEG for photos, PNG for graphics, SVG for icons).
-
Implementing lazy loading.
-
-
Caching: Storing copies of resources (images, scripts) locally to reduce server load and speed up page loads for repeat visitors. Controlled via HTTP cache headers (
Cache-Control,Expires). -
Display Resolution & Responsive Design: Users access sites on various devices (desktop, tablet, mobile). Use:
-
Fluid layouts (percentages,
max-width). -
Media queries (
@media) to apply different CSS based on screen size. -
Responsive images (
srcsetattribute).
-
Web 2.0 Concepts
-
Shift from Web 1.0: From static, read-only pages (brochure-ware) to dynamic, participatory platforms.
-
Key Features:
-
User-Generated Content: Blogs, wikis, social media posts.
-
Usability: Intuitive interfaces, AJAX for partial page updates.
-
Interoperability: APIs (REST, SOAP) allowing different systems to communicate.
-
Collaboration: Social networking, shared documents (Google Docs), crowdsourcing.
-
Rich User Experience: Rich Internet Applications (RIAs) using Flash (legacy), JavaScript frameworks.
-
UNIT 1: Markup Languages: HTML and XHTML
III. Markup Languages: HTML and XHTML
HTML Document Structure
<!DOCTYPE html> <!-- HTML5 declaration -->
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Page Title</title>
<!-- Metadata, CSS links, JS scripts -->
</head>
<body>
<!-- Visible page content -->
</body>
</html>
-
<!DOCTYPE html>: Tells the browser to render in standards mode. -
<html>: Root element. -
<head>: Metadata (title, charset, links to CSS/JS). Not displayed. -
<body>: Contains all visible content.
HTML Elements and Tags (Key Categories)
-
Text Formatting:
-
Headings:
<h1>(most important) to<h6>(least). -
Paragraph:
<p>...</p> -
Line Break:
<br>(empty element, no closing tag in HTML5).
-
-
Links (Anchor Tag):
<a href="https://www.example.com" target="_blank" title="Visit Example">Link Text</a>-
href: Destination URL (absolute or relative). -
target:_self(default),_blank(new tab),_parent,_top. -
title: Tooltip text.
-
-
Lists:
-
Ordered:
<ol><li>Item</li></ol>(numbered). -
Unordered:
<ul><li>Item</li></ul>(bulleted). -
Definition:
<dl><dt>Term</dt><dd>Description</dd></dl>.
-
-
Images:
<img src="image.jpg" alt="Description" width="300" height="200">-
src: Path to image file. -
alt: Critical for accessibility (screen readers) and SEO. Shown if image fails. -
width/height: Dimensions in pixels (prevents layout shift). -
Formats: JPEG (photos), PNG (transparency), GIF (animations), SVG (vector, scalable).
-
-
Tables:
<table border="1"> <tr><th>Header 1</th><th>Header 2</th></tr> <tr><td>Row 1, Cell 1</td><td rowspan="2">Spans 2 rows</td></tr> <tr><td>Row 2, Cell 1</td></tr> </table>-
<tr>: Table row. -
<td>: Table data cell. -
<th>: Table header cell (bold, centered by default). -
rowspan/colspan: Merge cells.
-
-
Forms and Form Controls:
<form action="process.php" method="post"> <label>Username: <input type="text" name="user" required></label><br> <label>Password: <input type="password" name="pass"></label><br> <label><input type="checkbox" name="agree"> I agree</label><br> Gender: <label><input type="radio" name="gender" value="m"> Male</label> <label><input type="radio" name="gender" value="f"> Female</label><br> <select name="city"> <option value="bhopal">Bhopal</option> <option value="indore" selected>Indore</option> </select><br> <textarea name="comment" rows="4" cols="50"></textarea><br> <input type="submit" value="Register"> <input type="reset" value="Clear"> </form>-
<form>: Container.action= processing script URL,method=get(URL) orpost(body). -
<input>:typedetermines control (text,password,checkbox,radio,submit,reset,hidden,email,numberetc.). -
Grouping Checkboxes vs. Radio Buttons:
-
Checkboxes: Multiple selections allowed. Same
nameattribute groups them logically, but each is independent. -
Radio Buttons: Only one selection per group. Must share the same
nameattribute to be mutually exclusive.
-
-
<select>&<option>: Dropdown list.selectedattribute sets default. -
<textarea>: Multi-line text input.rowsandcolsdefine size.
-
-
Frames and Framesets (Deprecated in HTML5):
<frameset cols="25%,*,25%"> <frame src="left.html" name="leftFrame"> <frame src="center.html" name="mainFrame"> <frame src="right.html" name="rightFrame"> </frameset>-
<frameset>: Replaces<body>. Defines rows/cols layout. -
<frame>: Defines individual HTML document within a frame. -
Targeting Links: Use
targetattribute in<a>(e.g.,target="mainFrame") to load link in a specific frame. -
Four Equal Parts:
<frameset rows="*,*" cols="*,*">creates a 2x2 grid.
-
XHTML
-
Definition: HTML reformulated as XML. Enforces stricter syntax rules.
-
Key Differences from HTML:
| Feature | HTML | XHTML | | :--- | :--- | :--- | | Syntax | Looser, forgiving | Strict XML rules | | Case Sensitivity | Tags/attributes not case-sensitive | All tags/attributes must be lowercase | | Closing Tags | Optional for some (e.g.,
<p>) | All elements must be closed (<br />,<img />) | | Quotes | Optional for attribute values | Attribute values must be in quotes | | Nesting | Some elements can overlap | Must be properly nested | -
Purpose: Enforces cleaner, more consistent code, better compatibility with XML tools.
HTML5
-
New Semantic Elements (improves SEO/accessibility):
-
<header>: Introductory content or group of navigational aids. -
<nav>: Major navigation block. -
<section>: Thematic grouping of content. -
<article>: Independent, self-contained composition (blog post, news story). -
<footer>: Footer for its nearest ancestor sectioning content/element. -
<aside>: Content tangentially related to surrounding content.
-
-
Enhanced Form Controls: New
typeattributes (email,url,tel,date,color,range,search). Built-in validation. -
Multimedia Support: Native
<audio>and<video>tags (no Flash plugin needed). -
Canvas & SVG:
<canvas>for dynamic 2D/3D drawing via JavaScript. Native support for SVG (Scalable Vector Graphics) inline.
Page Layout and Linking
-
Effective Layout: Use semantic HTML5 tags, CSS for positioning (Flexbox/Grid), maintain visual hierarchy, ensure accessibility.
-
Linking:
-
Internal vs. External: Link to a page within the same site vs. a different website.
-
Relative vs. Absolute Paths:
-
Absolute: Full URL (
https://example.com/page.html). Used for external links. -
Relative: Path from current document's location.
-
page.html(same directory) -
subfolder/page.html -
../page.html(parent directory)
-
-
Root-relative: Starts with
/(from website root)./images/logo.png.
-
-
UNIT 1: Cascading Style Sheets (CSS)
IV. Cascading Style Sheets (CSS)
Introduction to CSS
-
Purpose: Separates content (HTML) from presentation. Controls layout, colors, fonts, responsiveness.
-
Ways to Apply:
-
Inline:
styleattribute in HTML tag. (Highest specificity, hard to maintain).<p style="color: blue; font-size: 16px;">Text</p> -
Internal (Embedded):
<style>block in<head>. (Good for single-page styles).<head><style>p { color: blue; }</style></head> -
External: Separate
.cssfile linked via<link>. (Best practice - reusable, cacheable).<head><link rel="stylesheet" href="styles.css"></head>
-
CSS Syntax and Selectors
-
Rule Structure:
selector { property: value; /* declaration */ property: value; } -
Selector Types:
| Selector | Example | Selects | | :--- | :--- | :--- | | Element |
p| All<p>elements | | Class |.highlight| All elements withclass="highlight"| | ID |#header| Element withid="header"(unique per page) | | Pseudo-class |a:hover|<a>element when mouse hovers | | Descendant |div p| All<p>inside a<div>| | Child |ul > li| Direct child<li>of a<ul>|
Color Specification in CSS
-
Named Colors:
red,blue,lightseagreen,transparent. -
Hexadecimal:
#RRGGBBor#RGB(shorthand).#FF0000= red. -
RGB/RGBA:
-
rgb(255, 0, 0)(red). -
rgba(255, 0, 0, 0.5)(red with 50% opacity).
-
-
HSL/HSLA:
-
hsl(120, 100%, 50%)(green). Hue (0-360°), Saturation (%), Lightness (%). -
hsla(120, 100%, 50%, 0.5)(with alpha/opacity).
-
CSS for Presentation Enhancement
-
Text Formatting:
font-family,font-size,font-weight,font-style,text-align,text-decoration. -
Box Model (Core Concept):
+---------------------------+ | Margin |
| +---------------------+ | | | Border | | | | +---------------+ | | | | | Padding | | | | | | +-----------+ | | | | | | | Content | | | | | | | +-----------+ | | | | | +---------------+ | | | +---------------------+ |
+---------------------------+
```
* **Total Element Width** = `width + padding-left + padding-right + border-left + border-right + margin-left + margin-right`.
* **Default `box-sizing: content-box`** (width/height apply to content only).
* **Use `box-sizing: border-box`** (width/height include padding+border) for easier layout.
-
Positioning:
-
static(default, normal flow). -
relative: Offset from normal position (space remains). -
absolute: Removed from flow, positioned relative to nearest positioned ancestor (or viewport). -
fixed: Positioned relative to viewport (doesn't scroll). -
sticky: Actsrelativeuntil scroll threshold, thenfixed.
-
-
Layout Techniques:
-
Float:
float: left/right. Used for text wrap around images. Cleared withclear: both. -
Flexbox (
display: flex): 1D layout (row/column). Powerful for alignment/distribution. -
CSS Grid (
display: grid): 2D layout (rows & columns). Define grid tracks withgrid-template-columns/rows.
-
UNIT 1: Client-Side Scripting with JavaScript
V. Client-Side Scripting with JavaScript
Client-Side vs. Server-Side Scripting
| Feature | Client-Side (JS) | Server-Side (PHP, JSP) |
|---|---|---|
| Execution | In the user's browser | On the web server |
| Visibility | Code is visible to user (View Source) | Code is hidden on server |
| Primary Use | UI interactivity, form validation, dynamic content updates | Database access, business logic, generating HTML |
| Language | JavaScript (browser-dependent) | PHP, Python, Java, Ruby (server-dependent) |
| Example | Show/hide a div on button click | Fetch user data from MySQL database |
JavaScript Fundamentals
-
Syntax: Statements end with
;(optional). Code blocks{ }. Comments//or/* */. -
Variables: Declared with
let(block-scoped, reassignable),const(block-scoped, not reassignable), orvar(function-scoped, legacy). Uselet/const.let name = "Alice"; // string const PI = 3.14; // constant var age = 30; // avoid -
Data Types: Primitive:
String,Number,Boolean,undefined,null,BigInt,Symbol. Object (including arrays, functions). -
Operators: Arithmetic (
+,-,*,/,%), Assignment (=,+=), Comparison (==,===,!=,!==,>,<), Logical (&&,||,!). -
Control Structures:
// Conditionals if (condition) { ... } else if (condition2) { ... } else { ... } switch(expression) { case 'x': ... break; default: ... } // Loops for (let i=0; i<5; i++) { ... } while (condition) { ... } -
Functions:
function greet(name) { return "Hello " + name; } const multiply = (a, b) => a * b; // arrow function -
Events: Actions (click, load, submit) that JS can respond to.
<button onclick="myFunction()">Click</button>
Document Object Model (DOM)
-
Concept: A programming interface for HTML/XML documents. Represents the page as a tree of nodes (objects).
window | document | <html> / \ <head> <body> | <h1> <p> ... -
DOM Manipulation:
-
Accessing Elements:
document.getElementById('myId'); document.getElementsByClassName('myClass'); // HTMLCollection document.getElementsByTagName('p'); document.querySelector('.myClass'); // first match document.querySelectorAll('p'); // NodeList -
Modifying Content/Style:
element.innerHTML = "<b>New</b>"; element.textContent = "Plain text"; element.style.color = "red"; element.setAttribute('class', 'newClass'); -
Creating/Adding/Deleting:
const newEl = document.createElement('div'); newEl.textContent = "Hello"; parentElement.appendChild(newEl); element.remove(); // or parent.removeChild(element)
-
-
Event Handling:
const btn = document.getElementById('myBtn'); btn.addEventListener('click', function(event) { alert('Clicked!'); event.preventDefault(); // stop form submission });
Form Validation
-
Using Regular Expressions (Regex): Pattern matching for email, phone, password strength.
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; function validateEmail(email) { return emailRegex.test(email); } -
Validation Timing:
-
On Submit: Validate entire form in
onsubmithandler. Prevent submission if invalid. -
On-the-fly (Real-time): Validate individual fields on
onblur(lose focus) oroninputevents.
-
Dynamic HTML (DHTML)
-
Definition: A combination of HTML, CSS, and JavaScript used to create interactive, animated web pages without reloading.
-
Core Idea: Use JavaScript to dynamically change the DOM (content, structure, style) in response to user actions or timers.
-
Examples:
-
Show/hide elements (
element.style.display = 'none'). -
Animate elements by changing
left/toportransformproperties over time (setInterval). -
Update content without page refresh (AJAX - precursor to Fetch API).
-
UNIT 1: Data Representation with XML
VI. Data Representation with XML
XML Purpose and Advantages
-
Purpose: A meta-language for defining custom markup languages. Designed for data storage, configuration, and exchange between systems/platforms.
-
Advantages:
-
Platform Independent: Plain text, parsed by any XML parser.
-
Extensible: Users define their own tags and structure.
-
Self-Describing: Tags describe the data meaning.
-
Separates Data from Presentation: XML stores data; XSLT transforms it to HTML/other formats.
-
Supports Unicode: Global character sets.
-
XML Syntax and Structure
-
Well-Formedness Rules (Must follow to be valid XML):
-
Single Root Element: One top-level element encloses all others.
-
Case-Sensitive:
<Name>≠<name>. -
Proper Nesting:
<a><b></b></a>(OK),<a><b></a></b>(NOT OK). -
All Tags Closed:
<br />or<br></br>(empty tags can use shorthand). -
Attributes Quoted:
<person id="123">. -
Special Characters Escaped:
<(<),>(>),&(&),"("),'(').
-
-
XML Declaration (Optional but recommended):
<?xml version="1.0" encoding="UTF-8"?> -
Processing Instructions (PI): Instructions for applications (often for stylesheets).
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
Document Type Definition (DTD)
-
Purpose: Defines the legal structure, elements, and attributes of an XML document. Used for validation (ensuring document conforms to a defined structure).
-
Basic Syntax (Internal DTD example):
<!DOCTYPE note [ <!ELEMENT note (to,from,heading,body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)> ]> <note> <to>Alice</to> <from>Bob</from> <heading>Reminder</heading> <body>Don't forget the meeting.</body> </note>-
<!ELEMENT>: Defines an element and its content model (#PCDATA= parsed character data,(to,from)= sequence of child elements). -
<!ATTLIST>: Defines attributes for an element.
-
XML Schema vs. DTD
| Feature | DTD | XML Schema (XSD) |
|---|---|---|
| Syntax | Non-XML syntax (own format) | Written in XML itself |
| Data Types | Limited (#PCDATA, ID, IDREF) |
Rich built-in data types (xs:string, xs:date, xs:integer, xs:boolean) and custom types |
| Namespace Support | Poor | Full support (essential for modern web services) |
| Structure Definition | Simple content models | Complex types, sequences, choices, all groups, inheritance |
| Validation Power | Basic (structure only) | Advanced (data type, structure, cardinality) |
- Advantages of XSD: Stronger typing, extensibility, better integration with modern tools and web services (SOAP, REST).
XML Parsing Techniques
-
DOM (Document Object Model) Parser:
-
Loads the entire XML document into memory and builds a tree structure (node objects).
-
Pros: Easy navigation (parent/child/sibling), random access, can modify document.
-
Cons: Memory-intensive for large files.
-
Example (JavaScript):
const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlString, "text/xml"); const name = xmlDoc.getElementsByTagName("name")[0].textContent;
-
-
SAX (Simple API for XML) Parser:
-
Event-driven, sequential parsing. Reads document node-by-node and triggers events (
startElement,characters,endElement). -
Pros: Low memory footprint, fast for large files, can stop parsing early.
-
Cons: No random access, state must be managed manually in event handlers.
-
Example (Java):
SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); saxParser.parse(new File("file.xml"), new DefaultHandler() { public void startElement(String uri, String localName, String qName, Attributes attributes) { // Handle start of element } public void characters(char ch[], int start, int length) { // Handle text content } });
-
Naming Rules in XML
-
Names can contain letters, digits, hyphens (
-), underscores (_), and periods (.). -
Cannot start with a digit, hyphen, or period.
-
Cannot start with "xml" (case-insensitive, e.g.,
xml,Xml,XML). -
Cannot contain spaces.
-
Best Practices: Use meaningful names, be consistent (e.g.,
camelCaseorsnake_case), avoid colons (reserved for namespaces).
UNIT 1: Server-Side Scripting: PHP and JSP
VII. Server-Side Scripting: PHP and JSP
PHP: Introduction and Role
-
What is PHP?: "PHP: Hypertext Preprocessor". A server-side scripting language embedded in HTML. Code executes on the server, and the output (usually HTML) is sent to the client.
-
Role: Generate dynamic web pages, interact with databases, handle forms, manage sessions, build web applications.
-
Interpreters:
-
CLI (Command Line Interface): Run scripts from terminal.
-
CGI (Common Gateway Interface): Older, slower method. Server executes
php.exeas a separate process. -
Module (Apache/IIS): Most common & efficient. PHP runs as an integrated module within the web server process (e.g.,
mod_phpfor Apache).
-
PHP Basics
-
Syntax & Embedding:
<?php // PHP code here echo "Hello World"; ?> <!-- HTML outside PHP tags --> <?= "Shortcut for echo" ?> -
Variables: Start with
$. Dynamically typed (type determined by value).$name = "Alice"; // string $age = 25; // integer $price = 19.99; // float $isValid = true; // boolean -
Naming Rules:
-
Start with letter or underscore (
_), followed by letters, numbers, underscores. -
Case-sensitive (
$name≠$Name). -
No spaces.
-
-
String Manipulation:
$str = "This is my first program"; $$\displaystyle len = strlen( $$str); // 25 $$\displaystyle upper = strtoupper( $$str); $$\displaystyle sub = substr( $$str, 0, 4); // "This"
PHP Functions and Control Structures
-
Defining/Calling Functions:
function add($a, $b) { return $a + $b; } $result = add(5, 3); // 8 -
Conditionals & Loops: Similar to JS/C/Java.
if ($age >= 18) { ... } elseif (...) { ... } else { ... } switch($day) { case "Mon": ... break; ... } for ($$\displaystyle i=0; $$i<10; $i++) { ... } while ($condition) { ... } -
Simple Calculator Example:
<?php $$\displaystyle num1 = $$_POST['num1']; // from form $$\displaystyle num2 = $$_POST['num2']; $$\displaystyle op = $$_POST['operator']; switch($op) { case '+': $$\displaystyle result = $$num1 + $num2; break; case '-': $$\displaystyle result = $$num1 - $num2; break; case '*': $$\displaystyle result = $$num1 * $num2; break; case '/': $$\displaystyle result = $$num1 / $num2; break; } echo "Result: $result"; ?>
Object-Oriented Programming in PHP
-
Class & Object:
class User { public $name; // property public function greet() { // method return "Hello, " . $this->name; } } $user1 = new User(); $user1->name = "Bob"; echo $user1->greet(); -
Key OOP Concepts:
-
Encapsulation:
public,private,protectedaccess modifiers. -
Inheritance:
class Admin extends User { ... } -
Polymorphism: Method overriding in child classes.
-
PHP and MySQL Database Connectivity
-
Connection Methods (Use
mysqliorPDO-mysql_*functions are deprecated):-
MySQLi (Procedural):
$conn = mysqli_connect("localhost", "user", "pass", "dbname"); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "SELECT * FROM users"; $$\displaystyle result = mysqli_query( $$conn, $sql); while($$\displaystyle row = mysqli_fetch_assoc( $$result)) { ... } mysqli_close($conn); -
MySQLi (Object-Oriented):
$conn = new mysqli("localhost", "user", "pass", "dbname"); $$\displaystyle result = $$conn->query("SELECT * FROM users"); -
PDO (PHP Data Objects): Database-agnostic (works with MySQL, PostgreSQL, etc.). Recommended.
try { $pdo = new PDO("mysql:host=localhost;dbname=test", "user", "pass"); $$\displaystyle stmt = $$pdo->query("SELECT * FROM users"); foreach ($stmt as $row) { ... } } catch (PDOException $e) { ... }
-
-
CRUD Operations:
-
SELECT:
mysqli_query()/$pdo->query(). -
INSERT:
mysqli_query($conn, "INSERT INTO users (name) VALUES ('Alice')"). -
UPDATE:
... "UPDATE users SET name='Bob' WHERE id=1". -
DELETE:
... "DELETE FROM users WHERE id=1".
-
-
Add User to Login Table Example:
<?php $conn = new mysqli("localhost", "root", "", "mydb"); $$\displaystyle username = $$_POST['username']; $$\displaystyle password = password_hash( $$_POST['password'], PASSWORD_DEFAULT); // Always hash! $$\displaystyle sql = "INSERT INTO login (username, password) VALUES (' $$username', '$password')"; if ($$\displaystyle conn->query( $$sql) === TRUE) { echo "User added successfully"; } else { echo "Error: " . $$\displaystyle sql . "<br>" . $$conn->error; } $conn->close(); ?> -
Database Management:
-
Create:
CREATE DATABASE dbname;(viamysqli_query($conn, "CREATE DATABASE ...")). -
Select:
mysqli_select_db($conn, "dbname")or include in connection string. -
Delete:
DROP DATABASE dbname;.
-
Session Management with Cookies
-
Purpose of Cookies: Small text files stored on the client's browser. Used for session tracking, personalization, shopping carts.
- Session vs. Cookie: Session data is stored on the server (identified by a session ID, often stored in a cookie). Cookies store data on the client.
-
Setting/Reading Cookies in PHP:
// Set cookie (expires in 1 hour) setcookie("user", "Alice", time() + 3600, "/"); // Read cookie if (isset($_COOKIE["user"])) { echo "Welcome " . $_COOKIE["user"]; } -
Session Management (More Secure):
session_start(); // Must be first line $_SESSION['username'] = "Alice"; // Set session variable echo $_SESSION['username']; // Access session_destroy(); // End session
JavaServer Pages (JSP)
-
Introduction: Technology for creating dynamic web content using Java. JSP pages (
.jsp) are compiled into Servlets by the JSP container (Tomcat, Jetty). -
Using JavaBeans in JSP:
-
JavaBean: Reusable Java class with private properties, public getter/setter methods, and a no-arg constructor.
-
JSP Tags:
<jsp:useBean id="user" class="com.example.User" scope="session" /> <jsp:setProperty name="user" property="name" value="Alice" /> <jsp:getProperty name="user" property="name" />scope:page,request,session,application.
-
-
Session Tracking with Cookies in JSP:
-
Implicit Session Object:
HttpSession session = request.getSession();(automatically created/retrieved).<% session.setAttribute("username", "Alice"); %> Welcome, <%= session.getAttribute("username") %> -
Cookies:
<% Cookie cookie = new Cookie("user", "Alice"); cookie.setMaxAge(3600); response.addCookie(cookie); Cookie[] cookies = request.getCookies(); for (Cookie c : cookies) { out.println(c.getName() + ": " + c.getValue()); } %>
-
UNIT 1: Short Note Topics (Integrated Summary)
-
Advantages of PHP: Open-source, cross-platform, easy to learn (C-like syntax), huge community, extensive libraries, excellent database support, fast execution (with OPcache), embedded in HTML.
-
Function in PHP: Reusable block of code. Defined with
function name() { ... }. Can accept parameters and return values. Promotes modularity and reduces code duplication. -
Naming Rules in XML: Start with letter/underscore, no spaces, no "xml" prefix, case-sensitive. Use meaningful, consistent names.
-
Features of XHTML: Strict XML syntax (lowercase tags, closed tags, quoted attributes), enforces well-formedness, parsable by XML tools, promotes cleaner code.
-
Purpose of Cookies: Store small pieces of data on the client browser. Used for session tracking (maintaining login state), personalization (user preferences), and tracking (analytics).
-
Anchor Tag (
<a>): Creates hyperlink.hrefattribute specifies destination (URL).targetcontrols where link opens. Essential for web navigation. -
Heading Tags (
<h1>to<h6>): Define document headings/sections.<h1>is most important (primary title). Crucial for SEO and accessibility (document outline). -
Form Control Tags:
<form>(container),<input>(text, password, checkbox, radio, submit),<select>/<option>(dropdown),<textarea>(multi-line text). Used to collect user input. -
DHTML: Combination of HTML, CSS, and JavaScript to create dynamic, interactive web pages without server reloads. Involves DOM manipulation and scripting.
-
DTD (Document Type Definition): Defines the valid structure and elements of an XML document. Used for validation. Non-XML syntax, less powerful than XML Schema.
-
Features of HTML5: Semantic elements (
<header>,<nav>, etc.), native audio/video, new form input types/attributes, Canvas API, SVG support, Geolocation API, Web Storage, offline caching. -
Page Layout and Linking: Layout achieved via CSS (Flexbox/Grid). Linking uses
<a>withhref. Paths: absolute (full URL), relative (from current dir), root-relative (from site root). Crucial for site navigation.