Lab Final — Practice Hub

PHP & HTML/CSS
Solutions

All practice problems solved and ready to run. Study, understand, and ace your lab final.

5HTML / CSS
20PHP Problems
25Total Solutions
3MySQL CRUD
Download Lab Files Browse Solutions ↓

5 problems covering HTML forms, tables, CSS styling, colspan, alternating rows, and JavaScript form calculations. Open any .html file directly in your browser.

20 problems covering PHP functions, OOP (classes, inheritance, polymorphism), arrays, recursion, and MySQL CRUD. Run .php files with php filename.php (CLI) or via XAMPP for DB problems.

Available Products

ProductPrice ($)Qty Available
Laptop 999.9915
Mouse 25.00 50
Keyboard 45.00 30
Monitor 349.0010
` }, { num: 3, title: "Feedback Form", tags: ["html","css"], desc: "Name, Email, Rating (radio: Excellent/Good/Fair/Poor), Suggestions. Feedback table with alternating row colors.", lang: "html", code: ` Feedback Form

Feedback Form

Excellent   Good   Fair   Poor

Feedback Submissions

NameEmailRatingSuggestions
Alicealice@mail.comExcellentGreat service!
Bob bob@mail.com Good Could be faster.
Carolcarol@mail.comFair Needs improvement.
Daviddavid@mail.comExcellentLoved it!
` }, { num: 4, title: "Library Membership Form", tags: ["html","css"], desc: "Full Name, Email, Membership Type, Start Date, Tel. Opening Hours table with colspan for Friday 'Closed'.", lang: "html", code: ` Library Membership

Library Membership Registration

Regular   Premium   Student

Library Opening Hours

DayOpening TimeClosing Time
Monday 09:00 AM08:00 PM
Tuesday 09:00 AM08:00 PM
Wednesday 09:00 AM08:00 PM
Thursday 09:00 AM06:00 PM
Friday — Closed
Saturday 10:00 AM05:00 PM
Sunday 12:00 PM04:00 PM
` }, { num: 5, title: "Employee Details Table", tags: ["html","css"], desc: "Table with ID, Full Name, Position, Department, Salary. Alternating rows, bold salary, header background.", lang: "html", code: ` Employee Details

Employee Details

Employee IDFull NamePosition DepartmentSalary
E001Alice Johnson Software EngineerEngineering $85,000
E002Bob Martinez Product Manager Product $95,000
E003Carol White UX Designer Design $72,000
E004David Lee Data Analyst Analytics $78,000
E005Eve Thompson DevOps Engineer Engineering $90,000
E006Frank Adams HR Manager Human Resources$68,000
` } ]; // ───────────────────────────────────────────── const PHP_SOLUTIONS = [ { num: 1, title: "findmax() — Find Maximum", tags: ["php"], desc: "Returns the largest number in an array without using max().", lang: "php", code: ` $max) $max = $num; } return $max; } $nums = [15, 42, 8, 7]; echo "Maximum: " . findmax($nums) . PHP_EOL; // 42 $nums2 = [3, 99, 17, 54]; echo "Maximum: " . findmax($nums2) . PHP_EOL; // 99 ?>` }, { num: 2, title: "isPrime() — Check Prime", tags: ["php"], desc: "Checks if a number is prime. Only loops up to sqrt(n) for efficiency.", lang: "php", code: `` }, { num: 3, title: "Student Class", tags: ["php","oop"], desc: "Class with name, age, marks array. Methods: setDetails(), totalMarks(), averageMarks().", lang: "php", code: `name = $name; $this->age = $age; $this->marks = $marks; } public function totalMarks() { return array_sum($this->marks); } public function averageMarks() { return array_sum($this->marks) / count($this->marks); } public function display() { echo "Student: " . $this->name . " (Age: " . $this->age . ")" . PHP_EOL; echo "Marks: " . implode(", ", $this->marks) . PHP_EOL; echo "Total: " . $this->totalMarks() . PHP_EOL; echo "Average: " . $this->averageMarks() . PHP_EOL; } } $s = new Student(); $s->setDetails("Alice", 20, [85, 90, 78, 92, 88]); $s->display(); // Total: 433 | Average: 86.6 ?>` }, { num: 4, title: "factorial() — Recursive", tags: ["php"], desc: "Calculates n! recursively. Base case: n <= 1 returns 1.", lang: "php", code: `` }, { num: 5, title: "Product Class", tags: ["php","oop"], desc: "Class with name, price, stock. Methods: setDetails(), getDetails(), updateStock().", lang: "php", code: `name = $name; $this->price = $price; $this->stock = $stock; } public function getDetails() { echo "Product: " . $this->name . " | Price: $" . $this->price . " | Stock: " . $this->stock . PHP_EOL; } public function updateStock($sold) { if ($sold > $this->stock) { echo "Error: Not enough stock! (Available: " . $this->stock . ")" . PHP_EOL; } else { $this->stock -= $sold; echo "Sold " . $sold . " unit(s). Remaining: " . $this->stock . PHP_EOL; } } } $p = new Product(); $p->setDetails("Laptop", 999.99, 50); $p->getDetails(); $p->updateStock(5); $p->getDetails(); $p->updateStock(100); // Error: not enough stock ?>` }, { num: 6, title: "sortArray() — Bubble Sort", tags: ["php"], desc: "Sorts integers ascending using nested loops (bubble sort) — no built-in sort().", lang: "php", code: ` $arr[$j + 1]) { // swap adjacent elements [$arr[$j], $arr[$j + 1]] = [$arr[$j + 1], $arr[$j]]; } } } return $arr; } $nums = [5, 1, 4, 2, 3]; $sorted = sortArray($nums); echo "Original: " . implode(", ", $nums) . PHP_EOL; // 5,1,4,2,3 echo "Sorted: " . implode(", ", $sorted) . PHP_EOL; // 1,2,3,4,5 ?>` }, { num: 7, title: "Employee Salary — 10% Deduction", tags: ["php","oop"], desc: "Employee class with calculateSalary() returning salary after 10% deduction.", lang: "php", code: `name = $name; $this->monthlySalary = $salary; } public function calculateSalary() { return $this->monthlySalary * 0.90; // 10% deducted } } $emp1 = new Employee("John Doe", 5000); $emp2 = new Employee("Jane Smith", 8000); echo $emp1->name . " → Net: $" . $emp1->calculateSalary() . PHP_EOL; // $4500 echo $emp2->name . " → Net: $" . $emp2->calculateSalary() . PHP_EOL; // $7200 ?>` }, { num: 8, title: "findUnique() — Unique Elements", tags: ["php"], desc: "Returns array with duplicates removed using array_unique() + array_values().", lang: "php", code: `` }, { num: 9, title: "Library Class", tags: ["php","oop"], desc: "Library holds Book objects. Methods: addBook(), findByISBN().", lang: "php", code: `title = $title; $this->author = $author; $this->isbn = $isbn; } } class Library { private $bookList = []; public function addBook(Book $book) { $this->bookList[] = $book; echo "Added: \"" . $book->title . "\" by " . $book->author . PHP_EOL; } public function findByISBN($isbn) { foreach ($this->bookList as $book) { if ($book->isbn === $isbn) return $book; } return null; } } $lib = new Library(); $lib->addBook(new Book("PHP Basics", "John Smith", "ISBN-001")); $lib->addBook(new Book("MySQL in Action", "Jane Doe", "ISBN-002")); $found = $lib->findByISBN("ISBN-001"); if ($found) echo "Found: " . $found->title . " by " . $found->author . PHP_EOL; echo ($lib->findByISBN("ISBN-999") ? "Found" : "ISBN-999 not found.") . PHP_EOL; ?>` }, { num: 10, title: "Rectangle Class", tags: ["php","oop"], desc: "Class with length, width. Methods: setDimensions(), area(), perimeter().", lang: "php", code: `length = $length; $this->width = $width; } public function area() { return $this->length * $this->width; } public function perimeter() { return 2 * ($this->length + $this->width); } } $rect = new Rectangle(); $rect->setDimensions(8, 5); echo "Area: " . $rect->area() . PHP_EOL; // 40 echo "Perimeter: " . $rect->perimeter() . PHP_EOL; // 26 ?>` }, { num: 11, title: "reverseString()", tags: ["php"], desc: "Returns a string in reverse order by looping backwards from strlen-1 to 0.", lang: "php", code: `= 0; $i--) { $result .= $str[$i]; } return $result; } echo reverseString('hello') . PHP_EOL; // olleh echo reverseString('world') . PHP_EOL; // dlrow echo reverseString('racecar') . PHP_EOL; // racecar (palindrome) // PHP built-in shortcut: echo strrev('hello') . PHP_EOL; // olleh ?>` }, { num: 12, title: "MySQL SELECT — salary > 5000", tags: ["php","mysql"], desc: "Connects to MySQL and retrieves employees with salary > 5000. Needs XAMPP + db.php.", lang: "php", code: ` 5000"; $result = $conn->query($sql); if ($result && $result->num_rows > 0) { echo "Employees with salary > $5000:" . PHP_EOL; while ($row = $result->fetch_assoc()) { echo "ID: " . $row['id'] . " | Name: " . $row['name'] . " | Salary: $" . $row['salary'] . PHP_EOL; } } else { echo "No records found."; } $conn->close(); ?>` }, { num: 13, title: "fibonacci() — Recursive", tags: ["php"], desc: "Returns Fibonacci series up to n elements using recursion. Base cases: n=0,1,2.", lang: "php", code: `` }, { num: 14, title: "BankAccount Class", tags: ["php","oop"], desc: "Methods: deposit(), withdraw() (checks funds), checkBalance(). Demonstrates encapsulation.", lang: "php", code: `accountHolder = $holder; $this->balance = $balance; } public function deposit($amount) { $this->balance += $amount; echo "Deposited: $" . $amount . " | Balance: $" . $this->balance . PHP_EOL; } public function withdraw($amount) { if ($amount > $this->balance) { echo "Insufficient funds! (Balance: $" . $this->balance . ")" . PHP_EOL; } else { $this->balance -= $amount; echo "Withdrawn: $" . $amount . " | Balance: $" . $this->balance . PHP_EOL; } } public function checkBalance() { echo $this->accountHolder . "'s Balance: $" . $this->balance . PHP_EOL; } } $acc = new BankAccount("Alice", 1000); $acc->checkBalance(); // $1000 $acc->deposit(500); // $1500 $acc->withdraw(200); // $1300 $acc->withdraw(2000); // Insufficient funds $acc->checkBalance(); // $1300 ?>` }, { num: 15, title: "ShoppingCart Class", tags: ["php","oop"], desc: "Stores items (name, price, qty). Methods: addItem(), totalPrice() (price × qty sum).", lang: "php", code: `items[] = [ 'name' => $name, 'price' => $price, 'quantity' => $quantity, ]; $sub = $price * $quantity; echo "Added: " . $name . " (x" . $quantity . " @ $" . $price . ") = $" . $sub . PHP_EOL; } public function totalPrice() { $total = 0; foreach ($this->items as $item) { $total += $item['price'] * $item['quantity']; } return $total; } } $cart = new ShoppingCart(); $cart->addItem("Apple", 0.50, 4); // $2.00 $cart->addItem("Laptop", 999.00, 1); // $999.00 $cart->addItem("Pen", 1.50, 3); // $4.50 echo "Cart Total: $" . $cart->totalPrice() . PHP_EOL; // $1005.50 ?>` }, { num: 16, title: "Vehicle / Car — Inheritance", tags: ["php","oop"], desc: "Vehicle base class (make, model, year). Car extends it and adds doors. parent:: calls.", lang: "php", code: `make = $make; $this->model = $model; $this->year = $year; } public function display() { echo $this->year . " " . $this->make . " " . $this->model . PHP_EOL; } } class Car extends Vehicle { public $doors; public function __construct($make, $model, $year, $doors) { parent::__construct($make, $model, $year); // call parent constructor $this->doors = $doors; } public function display() { parent::display(); // reuse parent output echo " Doors: " . $this->doors . PHP_EOL; } } $v = new Vehicle("Honda", "CB500F", 2022); $v->display(); // 2022 Honda CB500F $c = new Car("Toyota", "Camry", 2023, 4); $c->display(); // 2023 Toyota Camry // Doors: 4 ?>` }, { num: 17, title: "MySQL INSERT Product (Form)", tags: ["php","mysql"], desc: "HTML form inserts into products table (id, name, price, quantity). Needs XAMPP + db.php.", lang: "php", code: `real_escape_string($_POST["name"]); $price = (float)$_POST["price"]; $quantity = (int)$_POST["quantity"]; $sql = "INSERT INTO products (name, price, quantity) VALUES ('$name', $price, $quantity)"; echo $conn->query($sql) ? "

Product added!

" : "

Error: " . $conn->error . "

"; } $conn->close(); ?> Add Product

Add New Product

Name:

Price:

Quantity:

` }, { num: 18, title: "findPrimesInRange()", tags: ["php"], desc: "Finds all primes between start and end (inclusive) using isPrime() helper.", lang: "php", code: `` }, { num: 19, title: "ContactBook Class", tags: ["php","oop"], desc: "Stores Contact objects. Methods: addContact(), removeContact(), searchContact() by name.", lang: "php", code: `name = $name; $this->phoneNumber = $phone; $this->email = $email; } } class ContactBook { private $contacts = []; public function addContact(Contact $c) { $this->contacts[] = $c; echo "Added: " . $c->name . PHP_EOL; } public function removeContact($name) { foreach ($this->contacts as $key => $c) { if (strtolower($c->name) === strtolower($name)) { unset($this->contacts[$key]); echo "Removed: " . $name . PHP_EOL; return; } } echo "Not found: " . $name . PHP_EOL; } public function searchContact($name) { foreach ($this->contacts as $c) { if (strtolower($c->name) === strtolower($name)) { echo "Found: " . $c->name . " | " . $c->phoneNumber . " | " . $c->email . PHP_EOL; return $c; } } echo "Not found: " . $name . PHP_EOL; return null; } } $book = new ContactBook(); $book->addContact(new Contact("Alice", "+1-555-0101", "alice@email.com")); $book->addContact(new Contact("Bob", "+1-555-0102", "bob@email.com")); $book->searchContact("Alice"); // Found $book->removeContact("Bob"); $book->searchContact("Bob"); // Not found ?>` }, { num: 20, title: "MySQL UPDATE Product (Form)", tags: ["php","mysql"], desc: "Fetch product by ID, pre-fill form, update name/price/quantity. Two-step GET then POST.", lang: "php", code: `real_escape_string($_POST["name"]); $price = (float)$_POST["price"]; $quantity = (int)$_POST["quantity"]; $sql = "UPDATE products SET name='$name', price=$price, quantity=$quantity WHERE id=$id"; echo $conn->query($sql) ? "

Updated!

" : "

Error: " . $conn->error . "

"; } $product = null; if (isset($_GET["id"])) { $id = (int)$_GET["id"]; $result = $conn->query("SELECT * FROM products WHERE id=$id"); $product = $result ? $result->fetch_assoc() : null; } $conn->close(); ?> Update Product

Update Product

Product ID:
Name:
Price:
Quantity:
` } ]; // ══════════════════════════════════════════════ // RENDER // ══════════════════════════════════════════════ function buildCard(sol) { const tagHTML = sol.tags.map(t => `${t}`).join(''); return `
${sol.num}
${sol.title}
${sol.desc}
${tagHTML}
${sol.lang || 'html'}
`; } function renderSolutions(list, containerId, langPrefix) { const container = document.getElementById(containerId); container.innerHTML = list.map(s => ({...s, lang: s.lang || langPrefix})).map(buildCard).join(''); container.querySelectorAll('pre code').forEach((el, i) => { el.textContent = list[i].code; hljs.highlightElement(el); }); } renderSolutions(HTML_SOLUTIONS, 'list-html', 'html'); renderSolutions(PHP_SOLUTIONS, 'list-php', 'php'); // ══════════════════════════════════════════════ // INTERACTIONS // ══════════════════════════════════════════════ function toggleCard(card) { card.classList.toggle('open'); } function switchTab(tab) { document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active')); document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active')); document.getElementById('panel-' + tab).classList.add('active'); document.getElementById(tab + '-tab').classList.add('active'); } function copyCode(btn) { const code = btn.closest('.card-body').querySelector('code').textContent; navigator.clipboard.writeText(code).then(() => { btn.textContent = 'Copied!'; btn.classList.add('ok'); setTimeout(() => { btn.textContent = 'Copy'; btn.classList.remove('ok'); }, 2000); }); } // Expand card when coming from anchor link window.addEventListener('hashchange', openFromHash); function openFromHash() { const hash = location.hash.slice(1); if (hash) { const el = document.getElementById(hash); if (el && el.classList.contains('card')) el.classList.add('open'); } }