Unit 1 of 1 · B.Sc IT Sem 4

Unit 1: PHP implementation and project work

Software Lab-VIII (Programming in PHP) notes · PTU syllabus (BSIT407)

4 min read11 topics10 exam questions
On this page
  1. Unit summary
  2. Setting up the environment
  3. Fundamentals and control structures
  4. Functions
  5. String manipulation
  6. Arrays
  7. Forms
  8. File handling
  9. Database connectivity with MySQL
  10. Cookies and sessions
  11. PHP project
  12. Version control and deployment
  13. Key terms
  14. Quick revision
  15. Important questions

Unit summary

This lab puts PHP into practice: programs on fundamentals and control structures, functions, string manipulation, arrays, forms, file handling, MySQL database connectivity, cookies and sessions, culminating in a complete PHP project.

After this unit you can

  • Set up a PHP and MySQL development environment
  • Write programs using control structures, functions, strings and arrays
  • Process forms, files and MySQL data
  • Build a PHP project with login and CRUD features

PTU syllabus topics

  • Implementation of programs covering PHP fundamentals
  • control structures
  • functions
  • string manipulation
  • arrays
  • forms
  • file handling
  • database connectivity with MySQL
  • cookies and sessions
  • culminating in a PHP project
ProcessBuilding a PHP-MySQL project
  1. 1

    Design the database

    Tables and keys

  2. 2

    Connect with mysqli or PDO

  3. 3

    Build forms

    Collect input

  4. 4

    Validate and save

    INSERT, UPDATE

  5. 5

    Display records

    SELECT into HTML tables

  6. 6

    Add login with sessions

1

Topic 1

Setting up the environment

ProcessLocal PHP setup
  1. 1Install XAMPP

    Apache + MySQL + PHP

  2. 2Start Apache and MySQL
  3. 3Put files in htdocs

    C:/xampp/htdocs/project

  4. 4Open localhost/project in the browser
  5. 5Create the database in phpMyAdmin

    localhost/phpmyadmin

2

Topic 2

Fundamentals and control structures

php<?php
// 1. Check whether a number is prime
$n = 29; $prime = $n > 1;
for ($i = 2; $i * $i <= $n; $i++) if ($n % $i == 0) { $prime = false; break; }
echo $n . ($prime ? " is prime" : " is not prime") . "<br>";

// 2. Fibonacci series of 10 terms
$a = 0; $b = 1;
for ($i = 1; $i <= 10; $i++) { echo $a . " "; [$a, $b] = [$b, $a + $b]; }

// 3. Reverse a number and check palindrome
$num = 12321; $rev = 0; $t = $num;
while ($t > 0) { $rev = $rev * 10 + $t % 10; $t = intdiv($t, 10); }
echo "<br>" . ($rev == $num ? "Palindrome" : "Not palindrome");

// 4. Day name with switch
switch (date("N")) {
    case 6: case 7: echo "<br>Weekend"; break;
    default: echo "<br>Weekday";
}
?>
3

Topic 3

Functions

php<?php
function factorial(int $n): int {            // recursive function
    return $n <= 1 ? 1 : $n * factorial($n - 1);
}
function simpleInterest($p, $r = 8, $t = 1) { // default arguments
    return $p * $r * $t / 100;
}
echo factorial(5);                 // 120
echo simpleInterest(5000);         // 400
$f = "factorial"; echo $f(4);      // dynamic function call: 24
?>
4

Topic 4

String manipulation

php<?php
$s = "Synetic Business School";
echo strlen($s), "<br>";                 // length
echo strtoupper($s), "<br>";
echo strrev($s), "<br>";                 // reverse
echo str_word_count($s), "<br>";         // 3
echo ucwords(strtolower("pHp lAB")), "<br>";
echo str_replace("School", "College", $s), "<br>";
$clean = strtolower(preg_replace("/[^a-z]/i", "", "Madam"));
echo $clean === strrev($clean) ? "Palindrome string" : "Not palindrome";
// count vowels
echo preg_match_all("/[aeiou]/i", $s);
?>
5

Topic 5

Arrays

php<?php
$marks = ["Aman" => 78, "Riya" => 91, "Kabir" => 66, "Simran" => 84];
arsort($marks);                              // sort by value, high to low
foreach ($marks as $name => $m) echo "$name: $m<br>";
echo "Average: " . array_sum($marks) / count($marks);
echo "Topper: " . array_key_first($marks);

// matrix addition
$A = [[1, 2], [3, 4]]; $B = [[5, 6], [7, 8]];
for ($i = 0; $i < 2; $i++) {
    for ($j = 0; $j < 2; $j++) echo ($A[$i][$j] + $B[$i][$j]) . " ";
    echo "<br>";
}
?>
6

Topic 6

Forms

php<?php
$result = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $a = (float) $_POST["a"]; $b = (float) $_POST["b"]; $op = $_POST["op"];
    $result = match ($op) {
        "+" => $a + $b, "-" => $a - $b, "x" => $a * $b,
        "/" => $b != 0 ? $a / $b : "Cannot divide by zero",
    };
}
?>
<form method="post">
  <input name="a" type="number" step="any" required>
  <select name="op"><option>+</option><option>-</option><option>x</option><option>/</option></select>
  <input name="b" type="number" step="any" required>
  <button>Calculate</button>
</form>
<p>Result: <?= htmlspecialchars((string) $result) ?></p>
  • Also practise: a registration form with validation (name, email, mobile, gender radio, hobbies checkboxes) that redisplays errors and entered values.
7

Topic 7

File handling

php<?php
// Visitor counter stored in a file
$file = "counter.txt";
$count = file_exists($file) ? (int) file_get_contents($file) : 0;
file_put_contents($file, ++$count);
echo "You are visitor number $count";

// Read a CSV file into an HTML table
echo "<table border='1'>";
if (($h = fopen("students.csv", "r")) !== false) {
    while (($row = fgetcsv($h)) !== false) {
        echo "<tr><td>" . implode("</td><td>", array_map("htmlspecialchars", $row)) . "</td></tr>";
    }
    fclose($h);
}
echo "</table>";
?>
8

Topic 8

Database connectivity with MySQL

sqlCREATE DATABASE college;
USE college;
CREATE TABLE student (
  roll INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(50) NOT NULL,
  course VARCHAR(20),
  marks INT
);
php<?php
// db.php — included by every page
$conn = new mysqli("localhost", "root", "", "college");
if ($conn->connect_error) die("Connection failed");

// add.php — insert from a form
require "db.php";
$stmt = $conn->prepare("INSERT INTO student (name, course, marks) VALUES (?, ?, ?)");
$stmt->bind_param("ssi", $_POST["name"], $_POST["course"], $_POST["marks"]);
$stmt->execute();

// list.php — display with edit and delete links
$res = $conn->query("SELECT * FROM student ORDER BY roll");
while ($r = $res->fetch_assoc()) {
    echo htmlspecialchars($r["name"]) . " — " . $r["marks"] .
         " <a href='edit.php?roll={$r['roll']}'>Edit</a>" .
         " <a href='delete.php?roll={$r['roll']}'>Delete</a><br>";
}
?>
9

Topic 9

Cookies and sessions

  • GET/POST feedback form: read with $_POST, validate, and display a thank-you message.
  • Contact form saved to a text file: file_put_contents("contacts.txt", "$name,$email\n", FILE_APPEND);
  • Session login:
php<?php
session_start();
if ($_POST["user"] === "admin" && password_verify($_POST["pwd"], $hash)) {
    $_SESSION["user"] = "admin";
    header("Location: dashboard.php");
} else {
    echo "Invalid login";
}
?>

Protect each private page with if (!isset($_SESSION["user"])) header("Location: login.php");

php<?php
// Remember the user's preferred theme for 30 days
if (isset($_GET["theme"])) setcookie("theme", $_GET["theme"], time() + 2592000);
$theme = $_COOKIE["theme"] ?? "light";
// Logout
session_start(); $_SESSION = []; session_destroy();
?>
10

Topic 10

PHP project

ProcessProject workflow
  1. 1

    Choose a topic

    Library, attendance, hostel, online quiz, inventory

  2. 2

    Requirements

    Users, features, reports

  3. 3

    Database design

    ER diagram and normalised tables

  4. 4

    Pages

    Login, dashboard, add, list, edit, delete, search, report

  5. 5

    Security

    Prepared statements, password_hash, session checks, input validation

  6. 6

    Testing and documentation

    Test cases, screenshots, project report

Example

Online quiz system: tables users, questions(id, question, a, b, c, d, answer), results(user_id, score, date); students log in, answer 10 random questions (ORDER BY RAND() LIMIT 10), see the score, and the admin views a results report.

11

Topic 11

Version control and deployment

Choose a blog system, inventory manager or task tracker with CRUD features, login and a clean layout.

  • Git basics: git init, git add ., git commit -m "message", git push to GitHub.
  • Deployment: upload files and the exported database to free hosting (for example InfinityFree) or demonstrate on localhost.

Exam tip

Viva favourites: "What is the difference between include and require?" (require stops on error), "Why hash passwords?", and "How do sessions work?"

Key terms

XAMPP
Package of Apache, MySQL, PHP and Perl for local development
htdocs
Folder from which Apache serves pages in XAMPP
Prepared statement
Parameterised SQL protecting against injection
password_hash
Function creating a secure password hash
CRUD
Create, read, update and delete operations

Quick revision

  • Install XAMPP; files in htdocs; phpMyAdmin.
  • Programs: prime, Fibonacci, palindrome, factorial, strings, arrays, matrices.
  • Forms with validation; files and CSV.
  • MySQL CRUD with prepared statements.
  • Cookies, sessions, project design and deployment.

Important exam questions

Practice questions written to the PTU exam pattern for this unit's syllabus: short answers (Section A style) and long answers (Sections B and C style).

Short-answer questions

  1. Q1.What is XAMPP?
  2. Q2.Distinguish include and require.
  3. Q3.How do you read a CSV file in PHP?
  4. Q4.Why are prepared statements used?
  5. Q5.How do you store a password securely in PHP?
  6. Q6.How do you protect a page so only logged-in users can see it?

Long-answer questions

  1. Q1.Write a PHP program to process a registration form with validation.
  2. Q2.Write PHP programs for insert, display, update and delete with MySQL.
  3. Q3.Write a PHP program using sessions for login and logout.
  4. Q4.Describe the design of a PHP project with its database and pages.

Stuck on this unit?

Message SBS on WhatsApp for help with Software Lab-VIII (Programming in PHP), or to ask about studying B.Sc IT at Synetic.

WhatsApp us