Web Programming I

ULTIMATE PRACTICAL + VIVA CHEAT SHEET

HTML • CSS • JavaScript • AJAX/XHR • PHP • Sessions • MySQL • CRUD • XML • DTD • Uploads • Multimedia • Error Handling

1. Exam Quick Map

Official structure: 10 practical coding questions → answer any 4 → 25 marks each → 100 marks total.
HTML
Structure, headings, paragraphs, lists, tables, images, links, forms, semantic tags.
CSS
Inline, internal, external, class, ID, grouping, nesting, layout.
PHP
Variables, functions, parameters, include/require, GET/POST, validation.
MySQL
Connect, INSERT, SELECT, UPDATE, DELETE.
XML
Well-formed XML and DTD validation.
Other practical topics
Multimedia, file upload, error handling, hosting/server concepts.

AJAX/XHR and PHP sessions are included here as extra study material based on your coursework request; they are not explicitly listed in the uploaded official Web Programming I scope.

2. HTML — Must Know

Basic Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Page</title>
</head>
<body>

</body>
</html>

Common Tags

PurposeTag
Heading<h1><h6>
Paragraph<p>
Link<a href="page.php">Open</a>
Image<img src="img.jpg" alt="Image">
Unordered list<ul><li>Item</li></ul>
Ordered list<ol><li>Item</li></ol>
Division<div>
Semantic<header> <nav> <main> <section> <article> <footer>

Table

<table border="1">
    <tr>
        <th>ID</th>
        <th>Name</th>
    </tr>
    <tr>
        <td>1</td>
        <td>Pasan</td>
    </tr>
</table>

Form

<form action="process.php" method="POST">
    <input type="text" name="name">
    <input type="email" name="email">
    <input type="password" name="password">

    <input type="radio" name="gender" value="Male"> Male
    <input type="radio" name="gender" value="Female"> Female

    <input type="checkbox" name="remember" value="1"> Remember

    <select name="course">
        <option value="web">Web</option>
        <option value="java">Java</option>
    </select>

    <textarea name="message"></textarea>
    <button type="submit">Submit</button>
</form>
Exam trap: PHP receives form values using the name attribute, not the HTML id.

3. CSS — Quick Reference

/* External CSS */
body {
    font-family: Arial;
    margin: 0;
}

.title {
    color: black;
}

#main {
    padding: 20px;
}

div p {
    margin: 5px;
}

h1, h2 {
    font-weight: bold;
}
SelectorExample
Elementp { }
Class.box { }
ID#header { }
Groupingh1, h2, p { }
Nesting/descendant.card p { }

Three Ways

<!-- Inline -->
<p style="color:red">Hello</p>

<!-- Internal -->
<style>
p { color:red; }
</style>

<!-- External -->
<link rel="stylesheet" href="style.css">

Responsive Layout

.container {
    width: min(1200px, 90%);
    margin: auto;
}

.grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
}

@media (max-width: 600px) {
    .grid {
        grid-template-columns: 1fr;
    }
}

4. JavaScript — DOM + Events

// Get element
var name = document.getElementById("name");

// Read value
var value = name.value;

// Change text
document.getElementById("msg").innerHTML = "Hello";

// Change input value
document.getElementById("name").value = "Pasan";

// Click event
function test() {
    alert("Hello");
}

Validation

function validate() {
    var name = document.getElementById("name").value;

    if (name == "") {
        alert("Name is required");
        return false;
    }

    return true;
}

Useful JS

parseInt("10");
parseFloat("10.5");
Number("20");

var x = 10;
if (x > 5) {
    console.log("Yes");
} else {
    console.log("No");
}

for (var i = 0; i < 5; i++) {
    console.log(i);
}

5. HTTP Request / Response — Core Idea

Client
Browser / JavaScript
Request
GET or POST sent to server
Server
Apache + PHP
Database
MySQL
Response
HTML / text / JSON
Browser
   |
   | HTTP Request
   | GET / POST
   v
Apache / PHP
   |
   | SQL
   v
MySQL
   |
   | Result
   v
PHP
   |
   | HTTP Response
   v
Browser
MethodTypical usePHP
GETRead/search data; parameters in URL$_GET["x"]
POSTSubmit/create/update data$_POST["x"]

6. AJAX — XMLHttpRequest Style

Viva answer: AJAX is a technique that allows JavaScript to communicate with a server asynchronously and update part of a web page without reloading the whole page.

XHR GET

var request = new XMLHttpRequest();

request.onreadystatechange = function () {
    if (request.readyState == 4 && request.status == 200) {

        var response = request.responseText;

        document.getElementById("content").innerHTML = response;
    }
};

request.open(
    "GET",
    "load-seller-process.php?page=1&search=pasan&status=1",
    true
);

request.send();

XHR POST + FormData

var form = new FormData();

form.append("e", document.getElementById("email").value);
form.append("p", document.getElementById("password").value);

var request = new XMLHttpRequest();

request.onreadystatechange = function () {
    if (request.readyState == 4 && request.status == 200) {

        var response = request.responseText;

        if (response == "success") {
            window.location = "home.php";
        } else {
            document.getElementById("msg").innerHTML = response;
        }
    }
};

request.open("POST", "signInProcess.php", true);
request.send(form);

XHR ReadyState

ValueMeaning
0Request not initialized
1Connection established
2Request received
3Processing
4Request finished / response ready

Important XHR Properties

Important: Use && for logical AND. Example: if (request.readyState == 4 && request.status == 200).

PHP endpoint for AJAX

<?php

$search = $_GET["search"];

echo "<h3>Search Result</h3>";
echo "You searched for: " . $search;

7. PHP Fundamentals

Basic PHP

<?php

$name = "Pasan";
$age = 20;

echo $name;
echo "<br>";
echo $age;

Conditions

if ($age >= 18) {
    echo "Adult";
} else {
    echo "Minor";
}

Function

function add($a, $b) {
    return $a + $b;
}

$result = add(10, 20);
echo $result;

GET / POST

// GET
$name = $_GET["name"];

// POST
$email = $_POST["email"];

Safe basic validation

if (!isset($_POST["email"]) || empty($_POST["email"])) {
    echo "Email is required";
    exit();
}

$email = trim($_POST["email"]);

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Invalid email";
    exit();
}

Include / Require

include "header.php";
include "footer.php";

require "Database.php";
Viva: include gives a warning if the file cannot be included; require is more strict and stops execution on failure.

8. PHP Form Processing

HTML

<form action="process.php" method="POST">
    <input type="text" name="name">
    <input type="email" name="email">
    <button type="submit">Save</button>
</form>

process.php

<?php

$name = $_POST["name"];
$email = $_POST["email"];

if ($name == "") {
    echo "Name required";
    exit();
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Invalid email";
    exit();
}

echo "Success";

Common $_POST types

$_POST["name"];
$_POST["email"];
$_POST["password"];

isset($_POST["remember"]);

9. PHP Sessions — Login System

Viva answer: A PHP session stores user information on the server so the application can remember a user between requests.

Login Process

<?php

session_start();

$email = $_POST["e"];
$password = $_POST["p"];

// After checking database credentials:
if ($valid) {

    $_SESSION["email"] = $email;

    echo "success";
} else {
    echo "Invalid email or password";
}

Protected Page

<?php

session_start();

if (!isset($_SESSION["email"])) {
    header("Location: index.php");
    exit();
}

echo "Welcome " . $_SESSION["email"];

Logout

<?php

session_start();

session_unset();
session_destroy();

header("Location: index.php");
exit();

Remember

session_start();

$_SESSION["user_id"] = 10;
$_SESSION["name"] = "Pasan";

echo $_SESSION["name"];

unset($_SESSION["name"]);

10. MySQL + PHP

Basic mysqli connection

<?php

$connection = new mysqli(
    "127.0.0.1",
    "root",
    "YOUR_DB_PASSWORD",
    "wpviva",
    3306
);

if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}

echo "Connected";

INSERT

$q = "INSERT INTO student(name, email)
      VALUES('Pasan', 'pasan@example.com')";

$connection->query($q);

SELECT

$q = "SELECT * FROM student";

$result = $connection->query($q);

while ($row = $result->fetch_assoc()) {
    echo $row["id"];
    echo $row["name"];
    echo $row["email"];
}

UPDATE

$q = "UPDATE student
       SET name='Kamal'
       WHERE id=1";

$connection->query($q);

DELETE

$q = "DELETE FROM student WHERE id=1";

$connection->query($q);
Production note: Real applications should use prepared statements instead of directly concatenating user input into SQL.

11. CRUD — Memorize This Pattern

OperationSQLPHP method
CreateINSERT INTO$connection->query()
ReadSELECT$connection->query() + fetch_assoc()
UpdateUPDATE ... SET ... WHERE$connection->query()
DeleteDELETE FROM ... WHERE$connection->query()

Complete Mini CRUD

<?php
require "Database.php";

// INSERT
Database::iud(
    "INSERT INTO student(name,email)
     VALUES('Pasan','pasan@example.com')"
);

// UPDATE
Database::iud(
    "UPDATE student
     SET name='New Name'
     WHERE id=1"
);

// DELETE
Database::iud(
    "DELETE FROM student
     WHERE id=1"
);

// SELECT
$result = Database::search(
    "SELECT * FROM student"
);

while ($row = $result->fetch_assoc()) {
    echo $row["name"] . "<br>";
}

12. Your Database Connection Class

This is the connection class you provided, formatted for the cheat sheet. The password is represented as a placeholder here so the cheat sheet does not permanently expose a database credential.
<?php

class Database
{
    public static $connection;

    public static function setUpConnection()
    {
        if (!isset(Database::$connection)) {

            Database::$connection = new mysqli(
                "127.0.0.1",
                "root",
                "YOUR_DB_PASSWORD",
                "wpviva",
                3306
            );
        }
    }

    public static function iud($q)
    {
        Database::setUpConnection();

        Database::$connection->query($q);
    }

    public static function search($q)
    {
        Database::setUpConnection();

        return Database::$connection->query($q);
    }
}

How to use it

<?php

require "Database.php";

// INSERT / UPDATE / DELETE
Database::iud(
    "INSERT INTO student(name,email)
     VALUES('Pasan','pasan@example.com')"
);

// SELECT
$result = Database::search(
    "SELECT * FROM student"
);

while ($row = $result->fetch_assoc()) {
    echo $row["name"];
}

Viva — Explain the class

13. File Upload

HTML

<form action="upload.php"
      method="POST"
      enctype="multipart/form-data">

    <input type="file" name="image">
    <button type="submit">Upload</button>

</form>

PHP

<?php

if (isset($_FILES["image"])) {

    $file = $_FILES["image"];

    $name = $file["name"];
    $tmp = $file["tmp_name"];
    $size = $file["size"];

    $destination = "uploads/" . basename($name);

    move_uploaded_file($tmp, $destination);

    echo "Upload successful";
}
KeyMeaning
$_FILES["image"]["name"]Original file name
tmp_nameTemporary uploaded file path
sizeFile size
typeMIME type supplied by upload

14. Multimedia

Image

<img src="image.jpg" alt="My Image" width="300">

Audio

<audio controls>
    <source src="song.mp3" type="audio/mpeg">
    Your browser does not support audio.
</audio>

Video

<video controls width="500">
    <source src="movie.mp4" type="video/mp4">
    Your browser does not support video.
</video>

15. XML + DTD

XML

<?xml version="1.0" encoding="UTF-8"?>

<students>
    <student>
        <id>1</id>
        <name>Pasan</name>
        <email>pasan@example.com</email>
    </student>
</students>

Internal DTD

<?xml version="1.0"?>
<!DOCTYPE students [
    <!ELEMENT students (student+)>
    <!ELEMENT student (id,name,email)>
    <!ELEMENT id (#PCDATA)>
    <!ELEMENT name (#PCDATA)>
    <!ELEMENT email (#PCDATA)>
]>

<students>
    <student>
        <id>1</id>
        <name>Pasan</name>
        <email>pasan@example.com</email>
    </student>
</students>
Viva: Well-formed XML follows XML syntax rules. A DTD defines the allowed structure/elements of the XML document.

16. Error Handling + Debugging

PHP

if (!$connection) {
    die("Database connection failed");
}

if (empty($name)) {
    echo "Name is required";
    exit();
}

JavaScript

try {
    // code
} catch (error) {
    console.log(error);
}

Common debugging checklist

  1. Check browser console for JavaScript errors.
  2. Check Network tab for GET/POST request and response.
  3. Check PHP syntax.
  4. Check Apache is running.
  5. Check MySQL is running.
  6. Check database name, username, password and port.
  7. Check form name attributes.
  8. Check PHP $_GET/$_POST keys.
  9. Check SQL query.
  10. Check file paths.

17. Viva — Rapid Fire

QuestionShort Answer
What is HTML?HTML defines the structure and content of a web page.
What is CSS?CSS controls the presentation and layout of a web page.
What is JavaScript?A programming language used to add behavior and interactivity to web pages.
What is PHP?A server-side scripting language commonly used to build dynamic web applications.
GET vs POST?GET normally sends parameters through the URL; POST sends data in the request body.
What is AJAX?A technique for asynchronous client-server communication without a full page reload.
What is XMLHttpRequest?A JavaScript API/object used to make HTTP requests and receive server responses.
What is FormData?A JavaScript object used to construct form data for sending to a server.
What is responseText?The response body received as text from the server.
What is readyState 4?The request has completed and the response is ready.
What is HTTP 200?The HTTP request was successfully handled at the protocol level.
What is a session?Server-side state used to remember information across requests.
Why session_start()?It starts or resumes the current PHP session.
What is CRUD?Create, Read, Update and Delete.
What is MySQL?A relational database management system.
What does mysqli do?It provides PHP functionality for communicating with MySQL.
What is SQL SELECT?It retrieves data from database tables.
What is XML?A markup format for representing structured data.
What is DTD?A definition of the allowed structure of an XML document.
Why enctype multipart/form-data?It is required for forms that upload files.
What is include?It inserts another PHP file into the current script.
What is require?It loads another PHP file and treats failure to load it as a fatal error.

18. Last-Minute Exam Memory

HTML
<form action="" method="POST">
<input name="x">
PHP
$x = $_POST["x"];
echo $x;
GET
$x = $_GET["x"];
AJAX GET
open("GET", "x.php", true);
send();
AJAX POST
var f = new FormData();
f.append("x", value);
send(f);
Session
session_start();
$_SESSION["x"] = $x;
Database
Database::iud($q);
Database::search($q);
SELECT
$r = Database::search($q);
$row = $r->fetch_assoc();
Exam strategy: First make the page work. Then add validation, styling, database operations and AJAX/session behavior. If something breaks, check the browser Console + Network tab and Apache/PHP/MySQL.