HTML · CSS · XML · XHTML · DOM
Web foundations — structure, styling, markup rules, and document models
Web foundations — structure, styling, markup rules, and document models
/. Self-closing: <br> <img> <hr><!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <!-- content here --> </body> </html>
<!DOCTYPE html> tells browser it's HTML5 — always the FIRST line!
<head> = metadata (invisible). <body> = actual visible content.
| Tag | Purpose | Output |
|---|---|---|
<h1>–<h6> | Headings | Largest → Smallest |
<p> | Paragraph | Block of text |
<strong> / <b> | Bold | Bold text |
<em> / <i> | Italic | Italic text |
<mark> | Highlight | Highlighted |
<br> | Line break | (self-closing) |
<a href="..."> | Hyperlink | Clickable link |
<img src="..." alt="..."> | Image | Displays image |
| Attribute | Meaning |
|---|---|
id | Unique ID for element |
class | Group style (CSS) |
src | File path / URL |
href | Link URL |
alt | Alt text for images (accessibility + fallback) |
title | Tooltip on hover |
| Type | href value |
|---|---|
| External | https://google.com |
| Internal | page2.html |
| Anchor | #section1 |
mailto:x@y.com |
| Type | Use |
|---|---|
text | Single line |
email | Email only |
password | Hidden text |
radio | One choice |
checkbox | Multi choice |
file | Upload |
<p style="color:red">
<style> inside <head>
<link rel="stylesheet" href="style.css"> — Best practice!
| Selector | Syntax | Targets |
|---|---|---|
| Element | p { } | All <p> tags |
| Class | .box { } | class="box" |
| ID | #header { } | id="header" |
| Universal | * { } | Everything |
| Descendant | div p { } | <p> inside <div> |
| Child | div > p { } | Direct child only |
| Pseudo-class | a:hover { } | On hover |
| Pseudo-element | p::first-line { } | First line only |
| CSS Property | Options / Example |
|---|---|
color | red, #ff0000, rgb(255,0,0) |
text-align | left | center | right | justify |
text-decoration | underline | overline | line-through |
text-transform | uppercase | lowercase | capitalize |
font-family | Arial, sans-serif |
font-size | 24px | 1.5em | 1.5rem |
font-weight | normal | bold | 100–900 |
| Margin Shorthand | Meaning |
|---|---|
margin: 10px | All 4 sides = 10px |
margin: 10px 20px | Top/Bottom | Left/Right |
margin: 10px 20px 15px | Top | L/R | Bottom |
margin: 10px 20px 15px 25px | Top Right Bottom Left (clockwise) |
content-box) only counts content.| Position | Behavior |
|---|---|
static | Default, normal document flow |
relative | Offset from its own normal position |
absolute | Removed from flow, placed relative to nearest positioned parent |
fixed | Always stays on screen (relative to viewport) |
sticky | Relative until scroll threshold, then fixed |
| CSS Units | Type | Notes |
|---|---|---|
px | Absolute | Fixed pixels |
% | Relative | Relative to parent |
em | Relative | Relative to parent font-size |
rem | Relative | Relative to root (html) font-size |
vw/vh | Relative | Viewport width / height |
<?xml version="1.0" encoding="UTF-8"?> <bookstore> <book id="1"> <title>Learning XML</title> <author>John Doe</author> <price>29.99</price> </book> </bookstore>
Defines structure and rules for an XML document — a blueprint of allowed elements.
Internal: small, single doc
External: reuse across many docs
More powerful than DTD. Supports data types, better validation, namespace support.
| Feature | DTD | XSD |
|---|---|---|
| Data types | No | Yes |
| Namespace | Limited | Full |
| Learning | Easy | Moderate |
| Character Entity | Code | Description |
|---|---|---|
| < | < | Less than |
| > | > | Greater than |
| & | & | Ampersand |
| (space) | | Non-breaking space |
| © | © | Copyright |
Client-side scripting with JS + Server-side Java Server Pages
| Inclusion Method | Syntax |
|---|---|
| Inline | <button onclick="fn()"> |
| Internal | <script>...</script> in head/body |
| External ✓ | <script src="app.js"></script> |
<script> at bottom of <body> so HTML loads first, or use defer attribute.let name = "John"; // String let age = 25; // Number let isStudent = true; // Boolean let x; // undefined const PI = 3.14; // constant // Template literal let msg = `Hello, ${name}!`;
| Type | Example | Notes |
|---|---|---|
| Number | let x = 25; 9.99 | Integers & decimals |
| String | "hello" 'world' | Text in quotes |
| Boolean | true / false | Logic values |
| Undefined | let x; | Declared, no value |
| Null | let x = null; | Intentionally empty |
| Object | { name: "John" } | Key-value pairs |
| Array | [1, 2, 3] | Ordered list |
== does type coercion (loose). === strict equality. Always prefer === in exams!typeof null returns "object" — JS quirk!if (marks >= 90) { console.log("Grade A"); } else if (marks >= 75) { console.log("Grade B"); // runs } else { console.log("Grade C"); }
switch(day) { case "Monday": console.log("Start"); break; // MANDATORY! case "Friday": console.log("TGIF"); break; default: console.log("Regular"); }
| Loop | Use When | Syntax |
|---|---|---|
for | Known count | for(init; cond; step) |
while | Unknown count | while(cond){} |
do-while | At least once | do{}while(cond) |
for...in | Object keys | for(k in obj) |
for...of | Iterable values | for(v of arr) |
| Array Method | Action | Returns |
|---|---|---|
push(x) | Add to end | New length |
pop() | Remove from end | Removed elem |
shift() | Remove from start | Removed elem |
unshift(x) | Add to start | New length |
indexOf(x) | Find index | Index or -1 |
slice(s,e) | Extract portion | New array |
splice(i,n) | Remove/insert | Removed items |
join(sep) | Array → string | String |
function greetUser(name) { return "Hello, " + name; }
const multiply = (a, b) => a * b; const square = x => x * x;
// Selecting elements document.getElementById("myBtn"); // by id document.getElementsByTagName("p"); // by tag document.querySelector(".class"); // first match document.querySelectorAll("div.box"); // all matches // Manipulation element.innerHTML = "New content"; element.style.color = "red"; // Events button.addEventListener("click", () => { alert("Clicked!"); });
document.getElementById("myForm") .addEventListener("submit", function(event) { event.preventDefault(); // stop default submit let name = document.getElementById("name").value; if (name.length < 2) { alert("Name must be ≥ 2 chars"); return; } alert("Form valid! Submitting..."); });
| Field | Regex Pattern |
|---|---|
/^[\s@]+@[^\s@]+\.[^\s@]+$/ | |
| Phone (10 digit) | /^[0-9]{10}$/ |
| Required field | value.trim() !== "" |
| Directive | Syntax | Purpose |
|---|---|---|
| page | <%@ page ... %> | Page-level settings |
| include | <%@ include file="x.jsp" %> | Static include (compile time) |
| taglib | <%@ taglib uri="..." prefix="c" %> | Custom tag libs (JSTL) |
jspService() — making JSP fast after warm-up.
| Feature | JSP | Servlet |
|---|---|---|
| File type | .jsp | .java |
| Focus | Presentation (HTML) | Logic/Controller |
| HTML | Easy inline HTML | out.println() needed |
| Behind scenes | Converted to Servlet! | Already a Servlet |
| Object | Type | Common Methods |
|---|---|---|
request | HttpServletRequest | getParameter(), getMethod() |
response | HttpServletResponse | setContentType(), sendRedirect() |
session | HttpSession | setAttribute(), getAttribute(), invalidate() |
application | ServletContext | setAttribute(), getAttribute() |
out | JspWriter | print(), println() |
public class Student implements java.io.Serializable { private String name; private int age; public Student() {} // no-arg constructor required public String getName() { return name; } public void setName(String n) { name = n; } }
| Bean Scope | Availability | Use Case |
|---|---|---|
| page | Current page only | Temp calculations |
| request | Current request | Form data passing |
| session | User's session | Login info, cart |
| application | All users, all pages | Site-wide config |
Server-side scripting, forms, file I/O, cookies, sessions
<?php $name = "John"; // String $age = 25; // Integer $height = 5.8; // Float $isStudent = true; // Boolean // Concatenation uses dot (.) echo "Name: " . $name; // if-elseif-else if ($score >= 90) { echo "Grade: A"; } elseif ($score >= 80) { echo "Grade: B"; } else { echo "Grade: F"; } ?>
$x = 5; is int, $x = "5"; is string. Use gettype($var) to check.// for loop for ($i=1; $i<=5; $i++) { echo $i . "<br>"; } // foreach (arrays) $fruits = ["Apple","Banana"]; foreach($fruits as $f) { echo $f; }
// function with default param function createProfile( $name, $age=18, $city="Unknown" ) { return "$name, $age"; } createProfile("Jatin"); // age=18, city=Unknown
| PHP Array Functions | What it does | Example |
|---|---|---|
count() | Number of elements | count($arr) → 3 |
array_push() | Add to end | array_push($arr,"x") |
array_pop() | Remove last | array_pop($arr) |
in_array() | Check if value exists | in_array("x",$arr) |
sort() | Sort ascending | sort($arr) |
array_merge() | Combine arrays | array_merge($a,$b) |
| Function | Purpose | Example → Result |
|---|---|---|
strlen($s) | Count chars | "Hello" → 5 |
strtoupper($s) | Uppercase | "php" → "PHP" |
strtolower($s) | Lowercase | "HELLO" → "hello" |
substr($s,0,3) | Substring | "Hello" → "Hel" |
str_replace($f,$r,$s) | Find & replace | "World"→"PHP" |
trim($s) | Remove whitespace | " hi " → "hi" |
explode(",",$s) | Split to array | "a,b" → ["a","b"] |
implode("-",$a) | Join to string | ["a","b"] → "a-b" |
strpos($s,$n) | Find position | returns int or false |
htmlspecialchars($s) | Escape HTML | XSS protection! |
strpos() returns 0 (not false) if found at position 0. Always use !== false, NOT != false.htmlspecialchars() when displaying user data to prevent XSS attacks. Use trim() to remove accidental spaces.<?php if ($_POST) { $username = $_POST['username']; $email = $_POST['email']; // Sanitize output echo htmlspecialchars($username); // Validation if (empty($username)) { echo "Username required"; } if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "Invalid email"; } } ?>
header("Location: page.php"); exit();// Read entire file $content = file_get_contents("data.txt"); echo $content; // Check file exists first! if (file_exists("data.txt")) { echo "File found!"; }
// Write (overwrites) file_put_contents("out.txt", $data); // Append to file file_put_contents( "out.txt", $newData, FILE_APPEND );
| File Mode (fopen) | Meaning |
|---|---|
"r" | Read only |
"w" | Write (overwrites) |
"a" | Append |
"r+" | Read + write |
fclose($file) when done — prevents memory leaks!setcookie() / $_COOKIEsession_start() / $_SESSION// Set cookie (1 hour) setcookie("username", "Jatin", time()+3600); // Read cookie if (isset($_COOKIE["username"])) { echo $_COOKIE["username"]; } // Delete cookie setcookie("username", "", time()-3600);
<?php session_start(); // MUST be first! $_SESSION["username"] = "Jatin"; $_SESSION["age"] = 20; echo $_SESSION["username"]; // Destroy session (logout) session_destroy(); ?>
setcookie() and session_start() must be called BEFORE any HTML output! Same rule as header().CRUD operations, SQL queries, state management, error handling
<?php $conn = mysqli_connect("localhost","root","","college"); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfully"; // ... do work ... mysqli_close($conn); // ALWAYS close! ?>
| Parameter | Value (example) | Meaning |
|---|---|---|
| host | "localhost" | Server address |
| username | "root" | DB username |
| password | "" | DB password |
| database | "college" | Target DB name |
$sql = "CREATE DATABASE college"; if (mysqli_query($conn, $sql)) { echo "DB created!"; }
mysqli_select_db($conn, "college"); // OR pass db name in connect() mysqli_connect("h","u","p","college");
// A) SELECT — Fetch Data $sql = "SELECT * FROM students"; $result = mysqli_query($conn, $sql); while ($row = mysqli_fetch_assoc($result)) { echo $row["name"] . " - " . $row["age"]; } // B) INSERT — Add Data $sql = "INSERT INTO students (name,age) VALUES ('Amit',21)"; mysqli_query($conn, $sql); // C) UPDATE — Modify Data $sql = "UPDATE students SET age=22 WHERE name='Amit'"; mysqli_query($conn, $sql); // D) DELETE — Remove Data $sql = "DELETE FROM students WHERE name='Amit'"; mysqli_query($conn, $sql);
| Function | Description |
|---|---|
mysqli_connect() | Connect PHP to MySQL server |
mysqli_query() | Execute SQL queries |
mysqli_fetch_assoc() | Fetch row as associative array ($row["name"]) |
mysqli_fetch_array() | Fetch row as numeric array ($row[0]) |
mysqli_error() | Return error message string |
mysqli_close() | Close the connection |
mysqli_connect_error() | Error on initial connection fail |
mysqli_select_db() | Switch to a specific database |
$row["Database"]$row[0]| Type | Full Name | Purpose | Commands |
|---|---|---|---|
| DDL | Data Definition | Define structure | CREATE, ALTER, DROP |
| DML | Data Manipulation | Modify data | INSERT, UPDATE, DELETE |
| DQL | Data Query | Retrieve data | SELECT |
SHOW DATABASES → no DB arg needed | SHOW TABLES → need DB selected first.
-- Add Column ALTER TABLE students ADD email VARCHAR(50); -- Modify Column ALTER TABLE students MODIFY age INT(3); -- Drop Column ALTER TABLE students DROP email; -- Template: ALTER TABLE tbl [ADD|MODIFY|DROP] col_name [TYPE]
| Operation | SQL Command | Effect |
|---|---|---|
| Delete Data | DELETE FROM | Removes rows only; table stays |
| Delete Table | DROP TABLE | Removes table + ALL data |
| Delete Database | DROP DATABASE | Removes DB + ALL tables + data |
welcome.php?name=Jatin&age=20 // Access: $_GET['name'] // retrieves "Jatin"
Convert arrays/objects to string for storage. Reverse with unserialize().
$data = ["name"=>"Jatin"]; $str = serialize($data); $back = unserialize($str); echo $back["name"]; // Jatin
| Error Type | Message | Cause | Fix |
|---|---|---|---|
| Connection | Access denied for user 'root' | Wrong username/password; MySQL not running | Check credentials; Start MySQL in XAMPP |
| DB Not Found | Unknown database 'college' | DB not created / typo | Run CREATE DATABASE first |
| Table Not Found | Table 'students' doesn't exist | Table not created / typo | Create table, verify name |
| SQL Syntax | You have an error in your SQL syntax | Missing commas/quotes, wrong keyword | Check syntax carefully |
| Duplicate Entry | Duplicate entry '1' for key 'PRIMARY' | Duplicate PRIMARY KEY value | Use AUTO_INCREMENT |
| Undefined Index | Undefined index: username | Accessing form data without checking | Use isset($_POST['username']) |
if(!$conn)isset() before accessing $_POST/$_GETDatabases & tables via GUI
Records in a form view
Execute queries in SQL tab
Backup & restore .sql files
localhost/phpmyadmin (requires XAMPP/WAMP running)Connect : mysqli_connect(host, user, pass, db) Create : CREATE DATABASE name | CREATE TABLE t (...) Insert : INSERT INTO t (col1,col2) VALUES (v1,v2) Select : SELECT * FROM t [WHERE condition] Update : UPDATE t SET col=val WHERE condition Delete : DELETE FROM t WHERE condition Drop : DROP TABLE t | DROP DATABASE db Cookie : setcookie(name, value, expiry) Session : session_start(); $_SESSION["key"]="val"