๐Ÿ“š Exam Study Guide

Web Application
Course Exam Prep

Everything you need to know โ€” clearly explained with real code examples.

25 marks ยท PHP
10 marks ยท JavaScript
5 marks ยท MVC / Laravel
๐Ÿ˜

PHP โ€” Basic PHP

Part of 25 marks

Variables & Data Types PHP

In PHP, variables start with $. PHP is loosely typed โ€” you don't declare the type.

php
<?php
// Variable types
$name   = "Alice";         // String
$age    = 22;              // Integer
$gpa    = 3.85;            // Float
$passed = true;            // Boolean
$grades = [85, 90, 78];  // Array

// Output
echo "Name: $name, Age: $age";

// String concatenation
echo "Hello " . $name . "!";

// Useful functions
strlen($name);        // string length
strtoupper($name);   // ALICE
strtolower($name);   // alice
count($grades);      // 3
?>

Control Flow โ€” if / else / loops PHP

php
<?php
// if-else
$marks = 75;
if ($marks >= 80) {
    echo "A grade";
} elseif ($marks >= 60) {
    echo "B grade";
} else {
    echo "C grade";
}

// for loop
for ($i = 1; $i <= 5; $i++) {
    echo $i . " ";   // 1 2 3 4 5
}

// foreach โ€” great for arrays
$fruits = ["apple", "mango", "banana"];
foreach ($fruits as $fruit) {
    echo $fruit . "<br>";
}

// while loop
$n = 1;
while ($n <= 3) {
    echo $n++;
}
?>

Functions PHP

php
<?php
// Define a function
function greet($name) {
    return "Hello, $name!";
}
echo greet("Bob");   // Hello, Bob!

// Default parameter
function add($a, $b = 10) {
    return $a + $b;
}
echo add(5);      // 15
echo add(5, 3);  // 8
?>
๐Ÿ“‹

PHP Forms

Part of 25 marks

GET vs POST PHP

$_GET

  • Data appears in URL
  • Used for searching/filtering
  • Not secure for passwords
  • ?name=Alice&age=22

$_POST

  • Data hidden in request body
  • Used for login, register, forms
  • More secure
  • No data in URL
html + php
<!-- HTML Form (form.html) -->
<form action="process.php" method="POST">
  <input type="text" name="username" placeholder="Your name">
  <input type="password" name="password">
  <button type="submit">Login</button>
</form>

<?php  // process.php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = htmlspecialchars($_POST["username"]);
    $password = $_POST["password"];

    echo "Welcome, $username";
}
?>
๐Ÿ’ก

htmlspecialchars() converts special characters like < and > into safe HTML entities. Always use it to prevent XSS attacks when displaying user input.

Form Validation PHP

php
<?php
$error = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = trim($_POST["email"]);
    $age   = $_POST["age"];

    // Check empty
    if (empty($email)) {
        $error = "Email is required";
    }
    // Validate email format
    elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Invalid email format";
    }
    // Validate age is numeric
    elseif (!is_numeric($age) || $age < 1) {
        $error = "Enter a valid age";
    } else {
        echo "Valid! Email: $email";
    }
}
?>
๐Ÿ›๏ธ

PHP OOP

Object-Oriented Programming ยท Part of 25 marks

Class, Object, Constructor PHP

A class is a blueprint. An object is a real instance created from that blueprint. The constructor runs automatically when you create an object.

php
<?php
class Student {
    // Properties (variables inside class)
    public $name;
    public $age;
    private $gpa;  // only accessible inside class

    // Constructor โ€” called when object is created
    public function __construct($name, $age, $gpa) {
        $this->name = $name;
        $this->age  = $age;
        $this->gpa  = $gpa;
    }

    // Method (function inside class)
    public function introduce() {
        return "I am {$this->name}, age {$this->age}";
    }

    // Getter for private property
    public function getGpa() {
        return $this->gpa;
    }
}

// Create objects
$s1 = new Student("Alice", 21, 3.9);
$s2 = new Student("Bob", 22, 3.5);

echo $s1->introduce();  // I am Alice, age 21
echo $s1->getGpa();    // 3.9
?>

Access Modifiers

  • public โ€” accessible everywhere
  • private โ€” only inside the class
  • protected โ€” inside class + child classes

Key Keywords

  • $this โ€” refers to current object
  • new โ€” creates an object
  • -> โ€” access property/method

Inheritance PHP

A child class extends a parent class and inherits all its public/protected properties and methods. Use parent:: to call the parent constructor.

php
<?php
class Animal {
    public $name;
    public function __construct($name) {
        $this->name = $name;
    }
    public function speak() {
        return "...";
    }
}

// Dog EXTENDS Animal (inherits everything)
class Dog extends Animal {
    public $breed;
    public function __construct($name, $breed) {
        parent::__construct($name); // call parent constructor
        $this->breed = $breed;
    }
    // Override parent method
    public function speak() {
        return "{$this->name} says: Woof!";
    }
}

$dog = new Dog("Rex", "Labrador");
echo $dog->speak();   // Rex says: Woof!
echo $dog->breed;    // Labrador
?>
๐Ÿ—„๏ธ

MySQL CRUD with PHP

Create ยท Read ยท Update ยท Delete ยท Part of 25 marks

CRUD Quick Reference SQL

OperationSQL StatementPurpose
CREATEINSERT INTOAdd new record
READSELECT ... FROMFetch records
UPDATEUPDATE ... SETModify existing record
DELETEDELETE FROMRemove record

Step 1 โ€” Connect to Database PHP

php (mysqli)
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db   = "school";

$conn = new mysqli($host, $user, $pass, $db);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected!";
?>

CREATE โ€” Insert Data PHP

php
<?php
$name = "Alice";
$age  = 21;

// Prepared statement (SAFE โ€” prevents SQL Injection)
$stmt = $conn->prepare("INSERT INTO students (name, age) VALUES (?, ?)");
$stmt->bind_param("si", $name, $age); // s=string, i=integer
$stmt->execute();

echo "Record inserted! ID: " . $conn->insert_id;
?>

READ โ€” Fetch Data PHP

php
<?php
// Fetch ALL students
$result = $conn->query("SELECT * FROM students");

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

// Fetch ONE student by ID (prepared)
$id   = 1;
$stmt = $conn->prepare("SELECT * FROM students WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$student = $result->fetch_assoc();

echo $student["name"];
?>

UPDATE โ€” Modify Data PHP

php
<?php
$newName = "Alice Smith";
$id      = 1;

$stmt = $conn->prepare("UPDATE students SET name = ? WHERE id = ?");
$stmt->bind_param("si", $newName, $id);
$stmt->execute();

echo "Updated! Rows affected: " . $stmt->affected_rows;
?>

DELETE โ€” Remove Data PHP

php
<?php
$id = 1;

$stmt = $conn->prepare("DELETE FROM students WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();

echo "Deleted successfully!";
$conn->close(); // Always close connection
?>
๐Ÿ’ก

Always use prepared statements (prepare + bind_param + execute) when taking user input. Never do: query("SELECT * WHERE id = $_GET['id']") โ€” that's SQL injection risk!

โšก

JavaScript

DOM Events ยท Arrays of Objects ยท Event Listeners ยท Nested Objects ยท 10 marks

DOM Events & getElementById JS

The DOM (Document Object Model) is the HTML page as a tree of objects. JavaScript can select elements and change them.

javascript
// Select elements
const box  = document.getElementById("myBox");
const items = document.querySelectorAll(".item");

// Change content & style
box.innerHTML = "<b>Updated!</b>";
box.style.color = "red";
box.style.display = "none";  // hide

// Change attribute
document.getElementById("img1").src = "new.jpg";

Event Listeners JS

Event listeners let you run code when something happens โ€” click, hover, typing, etc.

javascript
// Method 1: addEventListener (best practice)
const btn = document.getElementById("myBtn");

btn.addEventListener("click", function() {
    alert("Button clicked!");
});

// Arrow function style
btn.addEventListener("click", () => {
    document.getElementById("output").textContent = "Clicked!";
});

// Common events
btn.addEventListener("mouseover", () => { /* hover */ });
btn.addEventListener("mouseout",  () => { /* mouse leaves */ });

const input = document.getElementById("txtBox");
input.addEventListener("input", (e) => {
    console.log("Typed:", e.target.value);
});

input.addEventListener("keydown", (e) => {
    if (e.key === "Enter") console.log("Enter pressed");
});

Arrays of Objects JS

A very common pattern โ€” a list (array) of records (objects). You'll need to loop, filter, and display them.

javascript
// Array of objects
const students = [
    { id: 1, name: "Alice", gpa: 3.9 },
    { id: 2, name: "Bob",   gpa: 3.5 },
    { id: 3, name: "Carol", gpa: 3.7 },
];

// 1. Loop with forEach
students.forEach(s => {
    console.log(s.name, s.gpa);
});

// 2. filter โ€” get students with gpa > 3.6
const topStudents = students.filter(s => s.gpa > 3.6);
console.log(topStudents); // Alice, Carol

// 3. map โ€” transform into new array
const names = students.map(s => s.name);
console.log(names); // ["Alice", "Bob", "Carol"]

// 4. find โ€” get FIRST match
const bob = students.find(s => s.name === "Bob");
console.log(bob); // { id:2, name:"Bob", gpa:3.5 }

// 5. Display in HTML
const list = document.getElementById("studentList");
students.forEach(s => {
    list.innerHTML += `<li>${s.name} โ€” GPA: ${s.gpa}</li>`;
});

Nested Objects JS

Objects can contain other objects (or arrays) inside them. Access nested values with dot notation or bracket notation.

javascript
// Nested object
const student = {
    name: "Alice",
    age: 21,
    address: {              // nested object
        city: "Dhaka",
        zip: "1207"
    },
    courses: [              // array inside object
        { code: "CS101", grade: "A" },
        { code: "CS202", grade: "B+" }
    ]
};

// Access nested data
console.log(student.name);              // Alice
console.log(student.address.city);      // Dhaka
console.log(student.courses[0].code);  // CS101
console.log(student.courses[1].grade); // B+

// Loop through nested array
student.courses.forEach(c => {
    console.log(`${c.code}: ${c.grade}`);
});

// Modify nested value
student.address.city = "Chittagong";

Full Combined Example โ€” Events + DOM + Arrays JS

html + javascript
<input id="search" placeholder="Search student...">
<ul id="list"></ul>

<script>
const students = [
    { name: "Alice", dept: "CSE" },
    { name: "Bob",   dept: "EEE" },
    { name: "Carol", dept: "CSE" },
];

function renderList(data) {
    const list = document.getElementById("list");
    list.innerHTML = "";
    data.forEach(s => {
        list.innerHTML += `<li>${s.name} โ€” ${s.dept}</li>`;
    });
}

renderList(students); // initial render

// Live search on input event
document.getElementById("search")
    .addEventListener("input", (e) => {
        const q = e.target.value.toLowerCase();
        const filtered = students.filter(s =>
            s.name.toLowerCase().includes(q)
        );
        renderList(filtered);
    });
</script>
๐Ÿ—๏ธ

MVC Theory for Laravel

1 Theoretical Question ยท 5 marks

What is MVC? Theory

MVC stands for Model โ€“ View โ€“ Controller. It is a software design pattern that separates an application into three interconnected components so the code is organized, maintainable, and easy to scale.

M
Model
Data & Database
โ‡„
C
Controller
Logic & Bridge
โ‡„
V
View
UI & HTML

๐Ÿ”ท Model

  • Represents the data and business logic
  • Interacts with the database
  • In Laravel: Eloquent model class (e.g. Student.php)
  • Does NOT know about the UI

๐ŸŸก View

  • The UI shown to the user
  • HTML templates with dynamic data
  • In Laravel: Blade templates (.blade.php)
  • Does NOT contain business logic

๐ŸŸฃ Controller

  • The middleman between Model and View
  • Receives HTTP requests, processes logic, returns responses
  • In Laravel: a PHP class with methods (e.g. StudentController.php)
  • Tells the Model what data to fetch, then passes it to the View

How a Request Flows in Laravel MVC Theory

Here's what happens step by step when a user visits yoursite.com/students:

flow
1. User opens browser โ†’ requests /students

2. Laravel ROUTER (routes/web.php) matches the URL:
   Route::get('/students', [StudentController::class, 'index']);

3. CONTROLLER method runs (StudentController@index):
   โ†’ asks the MODEL for data

4. MODEL (Student.php - Eloquent):
   โ†’ queries the database
   โ†’ returns data to the Controller

5. CONTROLLER passes data to the VIEW:
   return view('students.index', ['students' => $students]);

6. VIEW (resources/views/students/index.blade.php):
   โ†’ renders HTML with the data
   โ†’ sends the final HTML page to the user's browser

Laravel Code Examples Laravel

routes/web.php
// Route โ†’ maps URL to Controller method
Route::get('/students', [StudentController::class, 'index']);
Route::post('/students', [StudentController::class, 'store']);
app/Http/Controllers/StudentController.php
class StudentController extends Controller {

    // READ โ€” show all students
    public function index() {
        $students = Student::all(); // Model fetches data
        return view('students.index', ['students' => $students]);
    }

    // CREATE โ€” save new student
    public function store(Request $request) {
        Student::create([
            'name' => $request->name,
            'age'  => $request->age,
        ]);
        return redirect()->route('students.index');
    }
}
app/Models/Student.php
class Student extends Model {
    // Fillable = allowed to mass-assign
    protected $fillable = ['name', 'age'];
}
// That's it! Eloquent handles all SQL automatically.
// Student::all() โ†’ SELECT * FROM students
// Student::find(1) โ†’ SELECT * FROM students WHERE id=1
resources/views/students/index.blade.php (View)
<h1>All Students</h1>
<ul>
    @foreach($students as $student)
        <li>{{ $student->name }} โ€” {{ $student->age }}</li>
    @endforeach
</ul>

Why Use MVC? โ€” The 5-Mark Answer Exam

โœ… Benefits

  • Separation of concerns โ€” each part has one job
  • Easier to maintain โ€” change UI without touching logic
  • Team collaboration โ€” designers work on Views, devs on Controllers
  • Reusability โ€” one Model used in many Views
  • Testability โ€” test each layer independently

๐Ÿ“ Sample Exam Answer

  • MVC separates an app into Model (data), View (UI), Controller (logic)
  • In Laravel, the Router directs requests to the Controller
  • The Controller queries the Eloquent Model for data
  • Data is passed to a Blade View for display
  • Benefits: organized code, easy maintenance, scalability
โญ

Remember this simple sentence: "MVC separates the application into three parts โ€” the Model handles data, the View handles display, and the Controller handles logic and acts as the bridge between them."