Unit 3 of 4 · B.Sc IT Sem 4

Unit 3: Forms, files and database connectivity

Programming in PHP notes · PTU syllabus (BSIT401)

3 min read8 topics10 exam questions
On this page
  1. Unit summary
  2. Working with forms and superglobal variables
  3. Importing and accessing user input
  4. Files: opening, copying, renaming and deleting
  5. Working with directories
  6. Generating images with PHP
  7. MySQL database connectivity
  8. DML operations: insert, update, delete and select
  9. Joins: cross, inner, outer and self
  10. Key terms
  11. Quick revision
  12. Important questions

Unit summary

Most PHP applications collect form data, store files and talk to a database. This unit covers forms and superglobal variables, importing user input, file and directory operations, generating images, MySQL connectivity, DML operations and joins.

After this unit you can

  • Process forms using superglobals
  • Open, copy, rename and delete files and work with directories
  • Generate images with PHP
  • Connect to MySQL and run DML queries and joins

PTU syllabus topics

  • Working with forms and superglobal variables
  • importing and accessing user input
  • opening/copying/renaming/deleting files
  • working with directories
  • generating images with PHP
  • MySQL database connectivity
  • DML operations (insert, delete, update, select)
  • joins (cross, inner, outer, self)
ComparisonSQL joins
Returns
Typical use

INNER JOIN

Only matching rows in both tables

Orders with their customers

LEFT JOIN

All left rows, plus matches

Customers even without orders

CROSS JOIN

Every combination of rows

Generating all pairs

SELF JOIN

A table joined to itself

Employees and their managers

1

Topic 1

Working with forms and superglobal variables

Key termsPHP superglobals
$_GET
Data sent in the URL query string
$_POST
Data sent in the request body
$_REQUEST
GET, POST and cookie data together
$_FILES
Uploaded files
$_COOKIE
Cookies sent by the browser
$_SESSION
Session variables
$_SERVER
Server and request details (PHP_SELF, REQUEST_METHOD, HTTP_USER_AGENT)
$_ENV / $GLOBALS
Environment and all global variables
2

Topic 2

Importing and accessing user input

php<?php
$errors = [];
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $name  = trim($_POST["name"] ?? "");
    $email = filter_var($_POST["email"] ?? "", FILTER_VALIDATE_EMAIL);
    $hobbies = $_POST["hobby"] ?? [];        // checkboxes named hobby[] arrive as an array
    if ($name === "") $errors[] = "Name is required";
    if (!$email)      $errors[] = "Invalid email";
    if (!$errors) echo "Thank you, " . htmlspecialchars($name);
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
  <input name="name"> <input name="email">
  <input type="checkbox" name="hobby[]" value="Music"> Music
  <input type="checkbox" name="hobby[]" value="Sports"> Sports
  <button>Submit</button>
</form>
  • Sticky forms re-display entered values after an error; self-processing forms post to the same page.
3

Topic 3

Files: opening, copying, renaming and deleting

Key termsfopen modes
r
Read only; file must exist
w
Write; creates or empties the file
a
Append; creates if missing
x
Create new; fails if it exists
r+ / w+ / a+
Read and write variants
php<?php
$f = fopen("students.txt", "a");
fwrite($f, "Aman,82\n");
fclose($f);

$f = fopen("students.txt", "r");
while (($line = fgets($f)) !== false) echo $line . "<br>";
fclose($f);

copy("students.txt", "backup.txt");          // copy
rename("backup.txt", "old/backup.txt");      // rename or move
if (file_exists("temp.txt")) unlink("temp.txt");   // delete
echo filesize("students.txt") . " bytes";
?>
4

Topic 4

Working with directories

php<?php
if (!is_dir("uploads")) mkdir("uploads", 0755);   // create
foreach (scandir("uploads") as $item) {             // list
    if ($item !== "." && $item !== "..") echo $item . "<br>";
}
$d = opendir("uploads");                            // older style
while (($entry = readdir($d)) !== false) echo $entry;
closedir($d);
rmdir("emptyfolder");                               // remove an empty directory
?>
5

Topic 5

Generating images with PHP

  • The GD library creates and edits images (PNG, JPEG, GIF) on the server — charts, thumbnails, CAPTCHAs, watermarks.
php<?php
header("Content-Type: image/png");
$img = imagecreatetruecolor(300, 120);
$bg  = imagecolorallocate($img, 240, 240, 255);
$blue = imagecolorallocate($img, 30, 60, 160);
imagefill($img, 0, 0, $bg);
imagerectangle($img, 5, 5, 294, 114, $blue);
imagestring($img, 5, 60, 50, "SBS Ludhiana", $blue);
imagepng($img);          // send to browser
imagedestroy($img);      // free memory
?>
6

Topic 6

MySQL database connectivity

ProcessPHP–MySQL connection steps
  1. 1Connect

    mysqli_connect(host, user, password, database) or new PDO(...)

  2. 2Check

    Stop with an error message if the connection fails

  3. 3Query

    Build SQL, preferably as a prepared statement

  4. 4Fetch

    Read rows with fetch_assoc()

  5. 5Close

    mysqli_close() or let the script end

php<?php
$conn = new mysqli("localhost", "root", "", "college");
if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);

$result = $conn->query("SELECT roll, name, marks FROM student");
while ($row = $result->fetch_assoc()) {
    echo $row["roll"] . " " . $row["name"] . " " . $row["marks"] . "<br>";
}
$conn->close();
?>
7

Topic 7

DML operations: insert, update, delete and select

php<?php
// INSERT with a prepared statement (prevents SQL injection)
$stmt = $conn->prepare("INSERT INTO student (name, marks) VALUES (?, ?)");
$stmt->bind_param("si", $name, $marks);          // s = string, i = integer
$stmt->execute();
echo "Inserted id " . $conn->insert_id;

// UPDATE
$stmt = $conn->prepare("UPDATE student SET marks = ? WHERE roll = ?");
$stmt->bind_param("ii", $newMarks, $roll);
$stmt->execute();
echo $stmt->affected_rows . " row(s) updated";

// DELETE
$stmt = $conn->prepare("DELETE FROM student WHERE roll = ?");
$stmt->bind_param("i", $roll);
$stmt->execute();

// SELECT with a condition
$stmt = $conn->prepare("SELECT name, marks FROM student WHERE marks >= ?");
$stmt->bind_param("i", $min);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
?>

Exam tip

Never put user input directly into SQL strings — "SELECT ... WHERE name = '$name'" invites SQL injection. Use prepared statements.

8

Topic 8

Joins: cross, inner, outer and self

  • Tables: student(roll, name, course_id) and course(id, title); employee(id, name, manager_id).
sql-- CROSS JOIN: every student with every course (Cartesian product)
SELECT s.name, c.title FROM student s CROSS JOIN course c;

-- INNER JOIN: only matching rows
SELECT s.name, c.title FROM student s INNER JOIN course c ON s.course_id = c.id;

-- LEFT OUTER JOIN: all students, course if any
SELECT s.name, c.title FROM student s LEFT JOIN course c ON s.course_id = c.id;

-- RIGHT OUTER JOIN: all courses, students if any
SELECT s.name, c.title FROM student s RIGHT JOIN course c ON s.course_id = c.id;

-- SELF JOIN: employee with their manager
SELECT e.name AS employee, m.name AS manager
FROM employee e LEFT JOIN employee m ON e.manager_id = m.id;
ComparisonJoin types
Rows returned
Typical use

Cross join

Every combination (m × n rows)

Generating combinations

Inner join

Only rows matching in both tables

Students with their course

Left or right outer join

All rows of one side plus matches

Students without a course

Self join

Table joined to itself

Employee–manager hierarchy

  • MySQL has no FULL OUTER JOIN; combine a LEFT and a RIGHT join with UNION.

Key terms

Superglobal
Predefined array available in every scope
Sticky form
Form that keeps entered values after submission
GD library
PHP extension for creating images
Prepared statement
SQL with placeholders filled safely later
Inner join
Join returning only matching rows

Quick revision

  • $_GET, $_POST, $_REQUEST, $_FILES, $_SERVER, $_SESSION, $_COOKIE.
  • Validate with filter_var; escape output with htmlspecialchars.
  • fopen modes; fwrite, fgets, copy, rename, unlink; mkdir, scandir, rmdir.
  • GD: imagecreatetruecolor, imagecolorallocate, imagestring, imagepng.
  • mysqli connect, prepare, bind_param, execute; INSERT, UPDATE, DELETE, SELECT; cross, inner, outer, self joins.

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.Name any four PHP superglobals.
  2. Q2.What is a sticky form?
  3. Q3.Distinguish fopen modes w and a.
  4. Q4.How is a file deleted in PHP?
  5. Q5.Why are prepared statements used?
  6. Q6.Distinguish inner and left outer joins.

Long-answer questions

  1. Q1.Explain form handling with superglobal variables and validation.
  2. Q2.Explain file and directory operations in PHP with programs.
  3. Q3.Explain PHP–MySQL connectivity and DML operations with code.
  4. Q4.Explain cross, inner, outer and self joins with examples.

Stuck on this unit?

Message SBS on WhatsApp for help with Programming in PHP, or to ask about studying B.Sc IT at Synetic.

WhatsApp us