Unit 3: Forms, files and database connectivity
Programming in PHP notes · PTU syllabus (BSIT401)
On this page
- Unit summary
- Working with forms and superglobal variables
- Importing and accessing user input
- Files: opening, copying, renaming and deleting
- Working with directories
- Generating images with PHP
- MySQL database connectivity
- DML operations: insert, update, delete and select
- Joins: cross, inner, outer and self
- Key terms
- Quick revision
- 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)
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
Topic 1
Working with forms and superglobal variables
- $_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
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.
Topic 3
Files: opening, copying, renaming and deleting
- 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";
?>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
?>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
?>Topic 6
MySQL database connectivity
- 1Connect
mysqli_connect(host, user, password, database) or new PDO(...)
- 2Check
Stop with an error message if the connection fails
- 3Query
Build SQL, preferably as a prepared statement
- 4Fetch
Read rows with fetch_assoc()
- 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();
?>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.
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;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
- Q1.Name any four PHP superglobals.
- Q2.What is a sticky form?
- Q3.Distinguish fopen modes w and a.
- Q4.How is a file deleted in PHP?
- Q5.Why are prepared statements used?
- Q6.Distinguish inner and left outer joins.
Long-answer questions
- Q1.Explain form handling with superglobal variables and validation.
- Q2.Explain file and directory operations in PHP with programs.
- Q3.Explain PHP–MySQL connectivity and DML operations with code.
- 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.
