student notes / est. for the classroom

HTML, CSS, JavaScript, Python, data science, computer networks — written the way you'd explain it to a classmate, not a compiler.

Top Job & Internship Portals

Handpicked portals for fresher jobs, tech roles, and listings in Hyderabad

GFG

GeeksforGeeks

Tech & Software Roles

Visit →
INT

Internshala

Fresher Jobs & Internships

Visit →
GOOG

Google Careers

Global Google Openings

Visit →
APN

Apna Jobs

Local Jobs in Hyderabad

Visit →
INS

Instahyre

Tech Roles in Hyderabad

Visit →
NAUK

Naukri.com

Fresher Jobs in Hyderabad

Visit →
๐Ÿ“ข Updated daily

Internship & Job Alerts

01

Latest notes

November 27, 2025

Web development with Fullstack

 

Unit 1: Frontend Development

Topics:

  • Introduction to Web Development (Frontend vs Backend vs Full-Stack)

  • HTML5: Elements, Forms, Semantic Tags

  • CSS3: Selectors, Flexbox, Grid, Animations, Responsive Design

  • JavaScript (ES6+): Variables, Functions, DOM Manipulation, Events

  • Advanced JS: ES6 modules, Fetch API

  • Introduction to a frontend framework/library (optional: React.js)

    • Components, Props, State

    • Event handling and forms

    • Routing (React Router or plain JS routing)

Practical:

  • Build a responsive multipage website (portfolio or task tracker)


Unit 2: Backend Development with PHP

Topics:

  • Introduction to PHP: Syntax, Variables, Data Types, Operators

  • Control structures (if, switch, loops)

  • Functions and arrays

  • Working with Forms and Superglobals ($_GET, $_POST, $_SESSION, $_COOKIE)

  • File handling (read/write files)

  • Object-Oriented PHP (classes, objects, inheritance)

  • Error handling in PHP

  • Introduction to Composer and PHP packages

Practical:

  • Build a basic PHP application (e.g., user registration/login form)

  • Handle form submissions and sessions


Unit 3: Database Management

Topics:

  • Introduction to databases: SQL basics

  • MySQL / MariaDB: Tables, Relationships, Joins

  • CRUD operations in SQL

  • Connecting PHP with MySQL using mysqli or PDO

  • Data validation and sanitization to prevent SQL Injection

  • Authentication and session management

  • Optional: Introduction to NoSQL (MongoDB) and connecting with PHP

Practical:

  • Build a PHP + MySQL CRUD application (e.g., blog or task manager)

  • Implement user authentication and role-based access


Unit 4: Full-Stack Integration & Deployment

Topics:

  • Connecting frontend with PHP backend

  • AJAX / Fetch API for asynchronous requests

  • RESTful API basics using PHP

  • File uploads and media management

  • Security best practices (sessions, cookies, data sanitization)

  • Deployment: Hosting PHP apps on XAMPP/LAMP, shared hosting, or cloud servers

  • Version control with Git/GitHub

  • Optional: Integrating a frontend framework (React/Vue) with PHP backend

Practical:

  • Build a full-stack PHP project (e-commerce, social media, or blog)

  • Deploy the project online

  • Implement login, CRUD operations, and database integration





Lab Program 1: Responsive Website using HTML5 & CSS3

Aim:
Design a responsive multipage website using modern HTML5 and CSS3.

Tasks:

  • Use semantic HTML tags

  • Design pages: Home, About, Contact

  • Apply Flexbox/Grid for layout

  • Make the site responsive using media queries

Unit Covered: Unit 1
Tools: HTML5, CSS3


Lab Program 2: JavaScript DOM Manipulation & Events

Aim:
Implement dynamic behavior using JavaScript.

Tasks:

  • DOM selection and manipulation

  • Event handling (click, submit)

  • Form validation using JavaScript

  • Dynamic content update

Unit Covered: Unit 1
Tools: JavaScript (ES6)


Lab Program 3: Task Tracker / Portfolio Website

Aim:
Build a responsive multipage frontend project.

Tasks:

  • Add navigation and routing (JS or React Router)

  • Use Fetch API to load data (JSON)

  • Use components (optional React)

  • Maintain state and props (if React)

Unit Covered: Unit 1
Outcome: Mini frontend project


Lab Program 4: PHP Basics & Control Structures

Aim:
Understand PHP syntax and programming fundamentals.

Tasks:

  • PHP variables, data types

  • Conditional statements and loops

  • Arrays and functions

  • Output HTML using PHP

Unit Covered: Unit 2
Tools: PHP


Lab Program 5: PHP Forms & Session Management

Aim:
Handle user input and sessions in PHP.

Tasks:

  • Create HTML form

  • Handle form submission using $_GET and $_POST

  • Implement sessions and cookies

  • Simple login validation

Unit Covered: Unit 2


Lab Program 6: Object-Oriented PHP Application

Aim:
Implement OOP concepts in PHP.

Tasks:

  • Create classes and objects

  • Use constructors and inheritance

  • Handle errors using try–catch

  • Build a reusable PHP class

Unit Covered: Unit 2


Lab Program 7: SQL & Database CRUD Operations

Aim:
Perform CRUD operations using SQL.

Tasks:

  • Create database and tables

  • Insert, update, delete, and fetch records

  • Use joins and constraints

Unit Covered: Unit 3
Tools: MySQL / MariaDB


Lab Program 8: PHP + MySQL CRUD Application

Aim:
Build a database-driven PHP application.

Tasks:

  • Connect PHP with MySQL using PDO / mysqli

  • Implement Create, Read, Update, Delete

  • Validate and sanitize inputs

  • Prevent SQL Injection

Example: Blog or Task Manager
Unit Covered: Unit 3


Lab Program 9: User Authentication & Role-Based Access

Aim:
Implement secure authentication system.

Tasks:

  • User registration and login

  • Password hashing

  • Session-based authentication

  • Role-based access (Admin/User)

Unit Covered: Unit 3 & 4


Lab Program 10: Full-Stack PHP Project & Deployment

Aim:
Develop and deploy a complete full-stack web application.

Options:

  • E-commerce website

  • Blog platform

  • Social media mini app

Tasks:

  • Frontend + PHP backend integration

  • AJAX / Fetch API

  • File upload handling

  • Deploy on XAMPP / shared hosting / cloud

  • Version control using GitHub

Unit Covered: Unit 4
Outcome: Capstone Project


LAB 1

๐Ÿ”น Lab Program 1: Responsive Website using HTML5 & CSS3

๐ŸŽฏ Aim

Design a responsive multi-page website using modern HTML5 and CSS3.


✅ Project Overview

You will create a 3-page website:

  • Home

  • About

  • Contact

Using:

  • Semantic HTML5 tags

  • Flexbox / CSS Grid

  • Media Queries for responsiveness


๐Ÿ“ Project Structure

responsive-website/ │ ├── index.html ├── about.html ├── contact.html └── css/ └── style.css

✅ 1️⃣ Use Semantic HTML5 Tags

Semantic tags improve readability and SEO.

Example Tags:

  • <header>

  • <nav>

  • <section>

  • <article>

  • <main>

  • <footer>


๐Ÿ  index.html (Home Page)

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Responsive Website</title> <link rel="stylesheet" href="css/style.css"> </head> <body> <header> <h1>My Responsive Website</h1> <nav> <a href="index.html">Home</a> <a href="about.html">About</a> <a href="contact.html">Contact</a> </nav> </header> <main> <section class="hero"> <h2>Welcome to Our Website</h2> <p>This site is built using HTML5 & CSS3.</p> </section> <section class="features"> <article> <h3>Fast</h3> <p>Optimized layout using Flexbox.</p> </article> <article> <h3>Responsive</h3> <p>Works on all screen sizes.</p> </article> <article> <h3>Modern</h3> <p>Built with semantic HTML5.</p> </article> </section> </main> <footer> <p>© 2026 My Website</p> </footer> </body> </html>

๐Ÿ“„ about.html

<main> <section> <h2>About Us</h2> <p>We create responsive websites using modern web technologies.</p> </section> </main>

(Include same header & footer as index.html)


๐Ÿ“„ contact.html

<main> <section> <h2>Contact Us</h2> <form> <input type="text" placeholder="Your Name"> <input type="email" placeholder="Your Email"> <textarea placeholder="Your Message"></textarea> <button type="submit">Send</button> </form> </section> </main>

✅ 2️⃣ Apply Flexbox / Grid Layout

๐Ÿ“„ css/style.css

* { margin: 0; padding: 0; box-sizing: border-box; font-family: Arial, sans-serif; } /* Header */ header { background: #333; color: white; padding: 15px; text-align: center; } nav { margin-top: 10px; } nav a { color: white; margin: 0 15px; text-decoration: none; } /* Hero Section */ .hero { text-align: center; padding: 40px; background: #f4f4f4; } /* Features using Flexbox */ .features { display: flex; justify-content: space-around; padding: 40px; } .features article { background: #ddd; padding: 20px; width: 30%; text-align: center; } /* Contact Form */ form { display: flex; flex-direction: column; width: 300px; margin: 20px auto; } form input, form textarea { margin-bottom: 10px; padding: 8px; } button { padding: 10px; background: #333; color: white; border: none; } /* Footer */ footer { text-align: center; padding: 15px; background: #222; color: white; margin-top: 20px; }

✅ 3️⃣ Make the Site Responsive (Media Queries)

Add at bottom of style.css:

@media (max-width: 768px) { .features { flex-direction: column; align-items: center; } .features article { width: 80%; margin-bottom: 20px; } nav a { display: block; margin: 10px 0; } }

๐Ÿ“ฑ Responsive Behavior

✔ Desktop → Horizontal layout
✔ Tablet → Adjusted spacing
✔ Mobile → Vertical stacked layout


๐Ÿ“Œ Expected Output

  • 3 fully linked pages

  • Semantic HTML structure

  • Flexbox layout

  • Responsive design

  • Clean modern UI


๐ŸŽฏ Learning Outcomes

After completing this lab, you can:

  • Use semantic HTML5 tags

  • Create multi-page websites

  • Use Flexbox for layouts

  • Apply media queries

  • Build responsive web designs


LAB 2

๐Ÿ”น Lab Program 2: JavaScript DOM Manipulation & Events

๐ŸŽฏ Aim

Implement dynamic behavior in a webpage using JavaScript.


✅ Tasks Covered

  • DOM selection and manipulation

  • Event handling (click, submit)

  • Form validation using JavaScript

  • Dynamic content updates


๐Ÿ“ Project Structure

dom-lab/ │ ├── index.html ├── style.css └── script.js

๐Ÿ“ index.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>DOM Manipulation Lab</title> <link rel="stylesheet" href="style.css"> </head> <body> <h1 id="main-title">JavaScript DOM Lab</h1> <button id="changeTextBtn">Change Title</button> <hr> <h2>Contact Form</h2> <form id="contactForm"> <input type="text" id="name" placeholder="Enter Name"> <input type="email" id="email" placeholder="Enter Email"> <button type="submit">Submit</button> </form> <p id="message"></p> <hr> <h2>Dynamic List</h2> <input type="text" id="itemInput" placeholder="Add item"> <button id="addItemBtn">Add Item</button> <ul id="itemList"></ul> <script src="script.js"></script> </body> </html>

๐ŸŽจ style.css (Optional Styling)

body { font-family: Arial, sans-serif; padding: 20px; } button { margin-top: 10px; padding: 8px; } input { display: block; margin-bottom: 10px; padding: 6px; } #message { margin-top: 10px; font-weight: bold; }

๐Ÿ’ป script.js


✅ 1️⃣ DOM Selection & Manipulation

const title = document.getElementById("main-title"); const changeBtn = document.getElementById("changeTextBtn"); changeBtn.addEventListener("click", function() { title.textContent = "Title Changed Successfully!"; title.style.color = "blue"; });

✔ getElementById()
✔ Modify text using textContent
✔ Change style dynamically


✅ 2️⃣ Event Handling (Click & Submit)

const form = document.getElementById("contactForm"); const message = document.getElementById("message"); form.addEventListener("submit", function(event) { event.preventDefault(); // Prevent page reload const name = document.getElementById("name").value; const email = document.getElementById("email").value; if (name === "" || email === "") { message.textContent = "All fields are required!"; message.style.color = "red"; } else { message.textContent = "Form submitted successfully!"; message.style.color = "green"; form.reset(); } });

✔ Handle form submit
✔ Prevent default behavior
✔ Validate inputs


✅ 3️⃣ Dynamic Content Update

const addItemBtn = document.getElementById("addItemBtn"); const itemInput = document.getElementById("itemInput"); const itemList = document.getElementById("itemList"); addItemBtn.addEventListener("click", function() { const itemText = itemInput.value; if (itemText !== "") { const li = document.createElement("li"); li.textContent = itemText; itemList.appendChild(li); itemInput.value = ""; } });

✔ Create elements dynamically
✔ Append elements to DOM
✔ Update content without page reload


๐Ÿ“Œ Expected Output

✔ Clicking "Change Title" updates heading
✔ Form validation shows error/success messages
✔ Items added dynamically to list
✔ No page reload during interactions


๐ŸŽฏ Learning Outcomes

After completing this lab, you can:

  • Select and manipulate DOM elements

  • Handle user events (click, submit)

  • Validate form inputs

  • Create dynamic content

  • Understand client-side interactivity


LAB 3

๐Ÿ”น Lab Program 3: Task Tracker / Portfolio Website

๐ŸŽฏ Aim

Build a responsive multi-page frontend project with navigation, dynamic data loading, and optional React component architecture.

You can implement this in:

  • ✅ Vanilla JavaScript (using Fetch API + simple routing)

  • ✅ Or React (recommended for advanced practice)


✅ Option 1: Vanilla JS Task Tracker (Using Fetch API)


๐Ÿ“ Project Structure

task-tracker/ │ ├── index.html ├── tasks.html ├── data.json ├── style.css └── script.js

๐Ÿ“ Step 1: Navigation (Multi-page)

index.html

<header> <h1>Task Tracker</h1> <nav> <a href="index.html">Home</a> <a href="tasks.html">Tasks</a> </nav> </header> <main> <h2>Welcome to Task Tracker</h2> </main>

๐Ÿ“„ data.json (Sample Data)

[ { "id": 1, "title": "Learn HTML", "status": "Completed" }, { "id": 2, "title": "Learn CSS", "status": "Pending" }, { "id": 3, "title": "Learn JavaScript", "status": "In Progress" } ]

๐Ÿ“„ tasks.html

<h2>Task List</h2> <ul id="taskList"></ul> <script src="script.js"></script>

๐Ÿ’ป script.js (Fetch API)

document.addEventListener("DOMContentLoaded", function () { const taskList = document.getElementById("taskList"); fetch("data.json") .then(response => response.json()) .then(data => { data.forEach(task => { const li = document.createElement("li"); li.textContent = `${task.title} - ${task.status}`; taskList.appendChild(li); }); }) .catch(error => { console.log("Error loading tasks:", error); }); });

๐Ÿ“Œ Features Implemented

✔ Navigation between pages
✔ Fetch API loads JSON data
✔ Dynamic task rendering
✔ Responsive layout using CSS


✅ Option 2: React-Based Task Tracker (Recommended)

Using React Router for navigation.


๐Ÿ“ Structure

src/ │ ├── components/ │ ├── Navbar.jsx │ └── TaskCard.jsx │ ├── pages/ │ ├── Home.jsx │ └── Tasks.jsx │ └── App.jsx

๐Ÿ”น Step 1: Routing Setup (App.jsx)

import { BrowserRouter as Router, Routes, Route } from "react-router-dom"; import Home from "./pages/Home"; import Tasks from "./pages/Tasks"; import Navbar from "./components/Navbar"; function App() { return ( <Router> <Navbar /> <Routes> <Route path="/" element={<Home />} /> <Route path="/tasks" element={<Tasks />} /> </Routes> </Router> ); } export default App;

๐Ÿ”น Navbar Component

import { Link } from "react-router-dom"; function Navbar() { return ( <nav> <Link to="/">Home</Link> | <Link to="/tasks">Tasks</Link> </nav> ); } export default Navbar;

๐Ÿ”น Tasks Page (Using Fetch API)

import { useState, useEffect } from "react"; function Tasks() { const [tasks, setTasks] = useState([]); useEffect(() => { fetch("/data.json") .then(res => res.json()) .then(data => setTasks(data)); }, []); return ( <div> <h2>Task List</h2> {tasks.map(task => ( <div key={task.id}> <h4>{task.title}</h4> <p>Status: {task.status}</p> </div> ))} </div> ); } export default Tasks;

๐Ÿ”น State & Props Example (TaskCard Component)

function TaskCard({ title, status }) { return ( <div> <h4>{title}</h4> <p>{status}</p> </div> ); }

Use it in Tasks:

{tasks.map(task => ( <TaskCard key={task.id} title={task.title} status={task.status} /> ))}

๐Ÿ“ฑ Responsive Layout Example (CSS)

nav { display: flex; justify-content: center; gap: 20px; } @media (max-width: 768px) { nav { flex-direction: column; align-items: center; } }

๐Ÿ“Œ Expected Output

✔ Multi-page navigation
✔ JSON data loaded dynamically
✔ Responsive layout
✔ Component-based structure (React option)
✔ State management using useState


๐ŸŽฏ Learning Outcomes

After completing this lab, you can:

  • Build multi-page frontend applications

  • Use Fetch API to load external data

  • Implement routing (Vanilla or React Router)

  • Manage state and props (React)

  • Structure projects professionally


LAB 4

๐Ÿงช Lab Program 4: PHP Basics & Control Structures

๐ŸŽฏ Aim

Understand PHP syntax and programming fundamentals.


✅ 1. PHP Variables & Data Types

๐Ÿ”น Example: index.php

<?php // Variables $name = "John"; $age = 22; $percentage = 85.5; $isStudent = true; // Displaying variables echo "<h2>Student Information</h2>"; echo "Name: " . $name . "<br>"; echo "Age: " . $age . "<br>"; echo "Percentage: " . $percentage . "%<br>"; echo "Student Status: " . ($isStudent ? "Yes" : "No") . "<br>"; ?>

๐Ÿ“Œ Data Types in PHP

  • String

  • Integer

  • Float

  • Boolean

  • Array

  • NULL

  • Object


✅ 2. Conditional Statements & Loops

๐Ÿ”น Conditional Example

<?php $marks = 75; if ($marks >= 90) { echo "Grade: A"; } elseif ($marks >= 70) { echo "Grade: B"; } elseif ($marks >= 50) { echo "Grade: C"; } else { echo "Fail"; } ?>

๐Ÿ”น Loop Examples

➤ For Loop

<?php for ($i = 1; $i <= 5; $i++) { echo "Number: $i <br>"; } ?>

➤ While Loop

<?php $count = 1; while ($count <= 5) { echo "Count: $count <br>"; $count++; } ?>

➤ Foreach Loop (for arrays)

<?php $subjects = array("Math", "Science", "English"); foreach ($subjects as $subject) { echo $subject . "<br>"; } ?>

✅ 3. Arrays & Functions

๐Ÿ”น Indexed Array

<?php $colors = ["Red", "Green", "Blue"]; echo $colors[0]; // Red ?>

๐Ÿ”น Associative Array

<?php $student = [ "name" => "Alice", "age" => 20, "course" => "BCA" ]; echo "Name: " . $student["name"]; ?>

๐Ÿ”น Function Example

<?php function greet($name) { return "Hello, " . $name . "!"; } echo greet("Rahul"); ?>

✅ 4. Output HTML using PHP

<?php $title = "Welcome Page"; ?> <!DOCTYPE html> <html> <head> <title><?php echo $title; ?></title> </head> <body> <h1><?php echo $title; ?></h1> <?php echo "<p>This content is generated using PHP.</p>"; ?> </body> </html>

๐Ÿงพ How to Run the Program

  1. Install XAMPP / WAMP

  2. Place the file inside htdocs folder

  3. Start Apache server

  4. Open browser:

    http://localhost/index.php

๐ŸŽฏ Expected Outcome

  • Understand PHP syntax

  • Use variables and data types

  • Implement conditionals and loops

  • Work with arrays and functions

  • Embed PHP inside HTML


LAB 5

๐Ÿงช Lab Program 5: PHP Forms & Session Management

๐ŸŽฏ Aim

Handle user input and sessions in PHP.


✅ 1. Create HTML Form

๐Ÿ”น File: login.html

<!DOCTYPE html> <html> <head> <title>Login Form</title> </head> <body> <h2>Login Form</h2> <form action="login.php" method="POST"> Username: <input type="text" name="username" required><br><br> Password: <input type="password" name="password" required><br><br> <input type="submit" value="Login"> </form> </body> </html>

✅ 2. Handle Form Submission using $_POST

๐Ÿ”น File: login.php

<?php session_start(); // predefined credentials $valid_username = "admin"; $valid_password = "1234"; // get form data $username = $_POST['username']; $password = $_POST['password']; // validation if ($username == $valid_username && $password == $valid_password) { // create session $_SESSION['username'] = $username; // create cookie (valid for 1 hour) setcookie("username", $username, time() + 3600); echo "Login successful!<br>"; echo "<a href='dashboard.php'>Go to Dashboard</a>"; } else { echo "Invalid username or password!"; } ?>

✅ 3. Using Sessions

๐Ÿ”น File: dashboard.php

<?php session_start(); // check session if (!isset($_SESSION['username'])) { echo "Please login first!"; exit(); } echo "<h2>Welcome, " . $_SESSION['username'] . "</h2>"; echo "<a href='logout.php'>Logout</a>"; ?>

✅ 4. Logout and Destroy Session

๐Ÿ”น File: logout.php

<?php session_start(); // destroy session session_destroy(); echo "You have been logged out.<br>"; echo "<a href='login.html'>Login Again</a>"; ?>

✅ 5. Using $_GET Example

๐Ÿ”น File: welcome.php

<?php $name = $_GET['name']; echo "Welcome, " . $name; ?>

Open in browser:

http://localhost/welcome.php?name=Rahul

Output:

Welcome, Rahul

✅ 6. Display Cookie Example

<?php if(isset($_COOKIE['username'])) { echo "Cookie Username: " . $_COOKIE['username']; } ?>

๐Ÿ“‚ Folder Structure

htdocs/ │ ├── login.html ├── login.php ├── dashboard.php ├── logout.php └── welcome.php

▶️ How to Run

  1. Install XAMPP / WAMP

  2. Start Apache server

  3. Place files in htdocs

  4. Open browser

    http://localhost/login.html

๐ŸŽฏ Expected Outcome

  • Create and handle HTML forms

  • Use $_GET and $_POST methods

  • Implement sessions

  • Implement cookies

  • Build simple login system


LAB 6

๐Ÿงช Lab Program 6: Object-Oriented PHP Application

๐ŸŽฏ Aim

Implement Object-Oriented Programming (OOP) concepts in PHP.


✅ 1. Create Classes and Objects

๐Ÿ”น Example: Basic Class

<?php class Student { public $name; public $age; public function setData($name, $age) { $this->name = $name; $this->age = $age; } public function display() { echo "Name: " . $this->name . "<br>"; echo "Age: " . $this->age . "<br>"; } } // Create object $student1 = new Student(); $student1->setData("Rahul", 21); $student1->display(); ?>

✅ 2. Constructors and Inheritance

๐Ÿ”น Example: Constructor

<?php class Person { protected $name; // Constructor public function __construct($name) { $this->name = $name; } public function greet() { echo "Hello, " . $this->name . "<br>"; } } $person1 = new Person("Anita"); $person1->greet(); ?>

๐Ÿ”น Example: Inheritance

<?php class Employee extends Person { private $salary; public function __construct($name, $salary) { parent::__construct($name); // Call parent constructor $this->salary = $salary; } public function showDetails() { echo "Name: " . $this->name . "<br>"; echo "Salary: " . $this->salary . "<br>"; } } $emp1 = new Employee("Ravi", 30000); $emp1->showDetails(); ?>

✅ 3. Error Handling using try–catch

<?php function divide($a, $b) { if ($b == 0) { throw new Exception("Division by zero is not allowed."); } return $a / $b; } try { echo divide(10, 2) . "<br>"; echo divide(10, 0); } catch (Exception $e) { echo "Error: " . $e->getMessage(); } ?>

✅ 4. Build a Reusable PHP Class (Example: Calculator)

๐Ÿ”น File: Calculator.php

<?php class Calculator { public function add($a, $b) { return $a + $b; } public function subtract($a, $b) { return $a - $b; } public function multiply($a, $b) { return $a * $b; } public function divide($a, $b) { if ($b == 0) { throw new Exception("Cannot divide by zero."); } return $a / $b; } } ?>

๐Ÿ”น Using the Reusable Class

<?php require 'Calculator.php'; $calc = new Calculator(); try { echo "Addition: " . $calc->add(10, 5) . "<br>"; echo "Division: " . $calc->divide(10, 2) . "<br>"; } catch (Exception $e) { echo "Error: " . $e->getMessage(); } ?>

๐Ÿ“‚ Suggested Folder Structure

htdocs/ │ ├── Calculator.php └── index.php

๐ŸŽฏ OOP Concepts Covered

✔ Class and Object
✔ Properties and Methods
✔ Constructor
✔ Inheritance
✔ Access Modifiers (public, private, protected)
✔ Exception Handling (try–catch)
✔ Reusable Class Design


๐Ÿ† Expected Outcome

After completing this lab, you can:

  • Develop modular PHP applications

  • Apply inheritance and encapsulation

  • Handle runtime errors safely

  • Create reusable PHP class libraries


LAB 7

๐Ÿงช Lab Program 7: SQL & Database CRUD Operations

๐ŸŽฏ Aim

Perform CRUD (Create, Read, Update, Delete) operations using SQL.


✅ 1. Create Database and Tables

๐Ÿ”น Step 1: Create Database

CREATE DATABASE college_db;
USE college_db;

๐Ÿ”น Step 2: Create Tables with Constraints

➤ Students Table

CREATE TABLE students ( student_id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50) NOT NULL, email VARCHAR(100) UNIQUE, age INT CHECK (age >= 18), department_id INT );

➤ Departments Table

CREATE TABLE departments ( department_id INT PRIMARY KEY AUTO_INCREMENT, department_name VARCHAR(50) NOT NULL );

➤ Add Foreign Key Constraint

ALTER TABLE students ADD CONSTRAINT fk_department FOREIGN KEY (department_id) REFERENCES departments(department_id) ON DELETE SET NULL;

✅ 2. Insert Records (CREATE)

๐Ÿ”น Insert into Departments

INSERT INTO departments (department_name) VALUES ('Computer Science'), ('Mechanical'), ('Electrical');

๐Ÿ”น Insert into Students

INSERT INTO students (name, email, age, department_id) VALUES ('Rahul', 'rahul@gmail.com', 20, 1), ('Anita', 'anita@gmail.com', 22, 2);

✅ 3. Fetch Records (READ)

๐Ÿ”น Select All

SELECT * FROM students;

๐Ÿ”น Select Specific Columns

SELECT name, email FROM students;

๐Ÿ”น Using WHERE Clause

SELECT * FROM students WHERE age > 20;

✅ 4. Update Records (UPDATE)

UPDATE students SET age = 23 WHERE student_id = 2;

✅ 5. Delete Records (DELETE)

DELETE FROM students WHERE student_id = 1;

✅ 6. Use Joins

๐Ÿ”น INNER JOIN Example

SELECT students.name, departments.department_name FROM students INNER JOIN departments ON students.department_id = departments.department_id;

๐Ÿ”น LEFT JOIN Example

SELECT students.name, departments.department_name FROM students LEFT JOIN departments ON students.department_id = departments.department_id;

✅ 7. Constraints Used

✔ PRIMARY KEY
✔ FOREIGN KEY
✔ UNIQUE
✔ NOT NULL
✔ CHECK
✔ AUTO_INCREMENT


๐Ÿ“‚ ER Diagram Concept (Logical Structure)

Departments (1) ---- (Many) Students
  • One department can have many students

  • Each student belongs to one department


▶️ How to Run

  1. Open MySQL / phpMyAdmin

  2. Execute queries step by step

  3. Verify using SELECT * FROM table_name;


๐ŸŽฏ Expected Outcome

After completing this lab, you can:

  • Create databases and tables

  • Apply constraints properly

  • Perform full CRUD operations

  • Write SQL joins

  • Maintain relational integrity


LAB 8

๐Ÿงช Lab Program 8: PHP + MySQL CRUD Application

๐ŸŽฏ Aim

Build a database-driven PHP application with secure CRUD operations.


✅ 1. Create Database & Table

CREATE DATABASE student_db; USE student_db; CREATE TABLE students ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(100) NOT NULL, email VARCHAR(100) UNIQUE NOT NULL, age INT NOT NULL );

๐Ÿ“‚ Project Structure

htdocs/ │ ├── config.php ├── index.php ├── add.php ├── edit.php ├── delete.php └── db.sql

✅ 2. Connect PHP with MySQL (Using PDO)

๐Ÿ”น config.php

<?php $host = "localhost"; $dbname = "student_db"; $username = "root"; $password = ""; try { $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { die("Connection failed: " . $e->getMessage()); } ?>

✔ Uses PDO
✔ Enables error mode
✔ Prevents SQL Injection via prepared statements


✅ 3. READ (Display Records)

๐Ÿ”น index.php

<?php require 'config.php'; $stmt = $pdo->query("SELECT * FROM students"); $students = $stmt->fetchAll(PDO::FETCH_ASSOC); ?> <h2>Student List</h2> <a href="add.php">Add Student</a> <table border="1"> <tr> <th>ID</th><th>Name</th><th>Email</th><th>Age</th><th>Action</th> </tr> <?php foreach ($students as $student): ?> <tr> <td><?= $student['id']; ?></td> <td><?= htmlspecialchars($student['name']); ?></td> <td><?= htmlspecialchars($student['email']); ?></td> <td><?= $student['age']; ?></td> <td> <a href="edit.php?id=<?= $student['id']; ?>">Edit</a> | <a href="delete.php?id=<?= $student['id']; ?>">Delete</a> </td> </tr> <?php endforeach; ?> </table>

✔ Uses htmlspecialchars() to prevent XSS


✅ 4. CREATE (Insert Data)

๐Ÿ”น add.php

<?php require 'config.php'; if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = htmlspecialchars(trim($_POST['name'])); $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); $age = intval($_POST['age']); if (!empty($name) && filter_var($email, FILTER_VALIDATE_EMAIL) && $age > 0) { $stmt = $pdo->prepare("INSERT INTO students (name, email, age) VALUES (?, ?, ?)"); $stmt->execute([$name, $email, $age]); header("Location: index.php"); exit(); } else { echo "Invalid input!"; } } ?> <form method="POST"> Name: <input type="text" name="name" required><br><br> Email: <input type="email" name="email" required><br><br> Age: <input type="number" name="age" required><br><br> <button type="submit">Add Student</button> </form>

✔ Input validation
✔ Prepared statement
✔ Prevents SQL Injection


✅ 5. UPDATE (Edit Data)

๐Ÿ”น edit.php

<?php require 'config.php'; $id = intval($_GET['id']); $stmt = $pdo->prepare("SELECT * FROM students WHERE id = ?"); $stmt->execute([$id]); $student = $stmt->fetch(PDO::FETCH_ASSOC); if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = htmlspecialchars(trim($_POST['name'])); $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); $age = intval($_POST['age']); $stmt = $pdo->prepare("UPDATE students SET name=?, email=?, age=? WHERE id=?"); $stmt->execute([$name, $email, $age, $id]); header("Location: index.php"); } ?> <form method="POST"> Name: <input type="text" name="name" value="<?= $student['name']; ?>" required><br><br> Email: <input type="email" name="email" value="<?= $student['email']; ?>" required><br><br> Age: <input type="number" name="age" value="<?= $student['age']; ?>" required><br><br> <button type="submit">Update</button> </form>

✅ 6. DELETE (Remove Data)

๐Ÿ”น delete.php

<?php require 'config.php'; $id = intval($_GET['id']); $stmt = $pdo->prepare("DELETE FROM students WHERE id = ?"); $stmt->execute([$id]); header("Location: index.php"); exit(); ?>

๐Ÿ” Security Measures Implemented

✔ PDO Prepared Statements
✔ Input validation (filter_var, intval, trim)
✔ XSS prevention (htmlspecialchars)
✔ SQL Injection prevention
✔ Server-side validation


▶️ How to Run

  1. Install XAMPP / WAMP

  2. Create database and table

  3. Place files inside htdocs

  4. Start Apache & MySQL

  5. Open:

    http://localhost/index.php

๐ŸŽฏ Expected Outcome

After completing this lab, you can:

  • Connect PHP with MySQL using PDO

  • Perform full CRUD operations

  • Validate and sanitize user input

  • Prevent SQL Injection

  • Build secure database-driven applications


LAB 9

๐Ÿงช Lab Program 9: User Authentication & Role-Based Access

๐ŸŽฏ Aim

Implement a secure authentication system with role-based access (Admin/User).


๐Ÿ—„️ 1️⃣ Database Setup

๐Ÿ”น Create Database & Table

CREATE DATABASE auth_db; USE auth_db; CREATE TABLE users ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(100) NOT NULL, email VARCHAR(150) UNIQUE NOT NULL, password VARCHAR(255) NOT NULL, role ENUM('admin','user') DEFAULT 'user' );

✔ ENUM ensures valid roles
✔ Password column supports hashed values


๐Ÿ“‚ Project Structure

htdocs/ │ ├── config.php ├── register.php ├── login.php ├── dashboard.php ├── admin.php ├── logout.php

๐Ÿ”— 2️⃣ Database Connection (PDO)

๐Ÿ”น config.php

<?php $host = "localhost"; $dbname = "auth_db"; $username = "root"; $password = ""; try { $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { die("Connection failed: " . $e->getMessage()); } session_start(); ?>

๐Ÿ“ 3️⃣ User Registration (Password Hashing)

๐Ÿ”น register.php

<?php require 'config.php'; if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = trim($_POST['name']); $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); $password = $_POST['password']; if (!empty($name) && filter_var($email, FILTER_VALIDATE_EMAIL) && strlen($password) >= 6) { $hashedPassword = password_hash($password, PASSWORD_DEFAULT); $stmt = $pdo->prepare("INSERT INTO users (name, email, password, role) VALUES (?, ?, ?, 'user')"); $stmt->execute([$name, $email, $hashedPassword]); echo "Registration successful! <a href='login.php'>Login</a>"; } else { echo "Invalid input!"; } } ?> <form method="POST"> Name: <input type="text" name="name" required><br><br> Email: <input type="email" name="email" required><br><br> Password: <input type="password" name="password" required><br><br> <button type="submit">Register</button> </form>

✔ Uses password_hash()
✔ Validates inputs
✔ Default role = user


๐Ÿ” 4️⃣ Login System (Session-Based Authentication)

๐Ÿ”น login.php

<?php require 'config.php'; if ($_SERVER["REQUEST_METHOD"] == "POST") { $email = $_POST['email']; $password = $_POST['password']; $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?"); $stmt->execute([$email]); $user = $stmt->fetch(PDO::FETCH_ASSOC); if ($user && password_verify($password, $user['password'])) { $_SESSION['user_id'] = $user['id']; $_SESSION['name'] = $user['name']; $_SESSION['role'] = $user['role']; header("Location: dashboard.php"); exit(); } else { echo "Invalid credentials!"; } } ?> <form method="POST"> Email: <input type="email" name="email" required><br><br> Password: <input type="password" name="password" required><br><br> <button type="submit">Login</button> </form>

✔ Uses password_verify()
✔ Secure session storage


๐Ÿ‘ค 5️⃣ User Dashboard (Protected Page)

๐Ÿ”น dashboard.php

<?php require 'config.php'; if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit(); } echo "<h2>Welcome, " . $_SESSION['name'] . "</h2>"; echo "Role: " . $_SESSION['role'] . "<br><br>"; if ($_SESSION['role'] == 'admin') { echo "<a href='admin.php'>Go to Admin Panel</a><br><br>"; } echo "<a href='logout.php'>Logout</a>"; ?>

✔ Session-based authentication
✔ Redirect if not logged in


๐Ÿ› ️ 6️⃣ Role-Based Access (Admin Only Page)

๐Ÿ”น admin.php

<?php require 'config.php'; if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') { echo "Access Denied!"; exit(); } echo "<h2>Admin Panel</h2>"; echo "Only admins can access this page."; ?>

✔ Admin-only restriction
✔ Role-based validation


๐Ÿšช 7️⃣ Logout

๐Ÿ”น logout.php

<?php require 'config.php'; session_destroy(); header("Location: login.php"); exit(); ?>

๐Ÿ” Security Features Implemented

✔ Password hashing (password_hash)
✔ Password verification (password_verify)
✔ PDO prepared statements
✔ Session-based authentication
✔ Role-based access control
✔ Input validation & sanitization


▶️ How to Run

  1. Start XAMPP / WAMP

  2. Create database & table

  3. Place files inside htdocs

  4. Open browser:

    http://localhost/register.php

๐ŸŽฏ Expected Outcome

After completing this lab, you can:

  • Build secure authentication systems

  • Hash and verify passwords properly

  • Manage user sessions

  • Implement role-based authorization

  • Protect pages from unauthorized access


LAB 10

๐Ÿงช Lab Program 10: Full-Stack PHP Project & Deployment

๐ŸŽฏ Aim

Develop and deploy a complete full-stack web application using PHP & MySQL.


✅ Project Option (Recommended Example)

๐Ÿ“ Blog Platform (Full-Stack PHP + MySQL)

You can adapt the same structure for:

  • ๐Ÿ›’ E-commerce website

  • ๐Ÿ“ฑ Social media mini app


๐Ÿ“‚ Project Architecture

blog_app/ │ ├── config.php ├── index.php ├── login.php ├── register.php ├── dashboard.php ├── create_post.php ├── upload/ ├── assets/ │ ├── css/ │ └── js/ └── database.sql

๐Ÿ—„️ 1️⃣ Database Structure

CREATE DATABASE blog_db; USE blog_db; CREATE TABLE users ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(100), email VARCHAR(150) UNIQUE, password VARCHAR(255) ); CREATE TABLE posts ( id INT PRIMARY KEY AUTO_INCREMENT, title VARCHAR(255), content TEXT, image VARCHAR(255), user_id INT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE );

๐Ÿ”— 2️⃣ Frontend + PHP Backend Integration

๐Ÿ”น config.php (PDO Connection)

<?php $pdo = new PDO("mysql:host=localhost;dbname=blog_db", "root", ""); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); session_start(); ?>

๐Ÿ” 3️⃣ User Authentication (Backend Integration)

Use:

  • password_hash()

  • password_verify()

  • Sessions for login

(Reuse Lab 9 authentication logic)


✍️ 4️⃣ Create Blog Post (With File Upload)

๐Ÿ”น create_post.php

<?php require 'config.php'; if ($_SERVER["REQUEST_METHOD"] == "POST") { $title = htmlspecialchars($_POST['title']); $content = htmlspecialchars($_POST['content']); $user_id = $_SESSION['user_id']; // File Upload $imageName = $_FILES['image']['name']; $tempName = $_FILES['image']['tmp_name']; $uploadPath = "upload/" . basename($imageName); if (move_uploaded_file($tempName, $uploadPath)) { $stmt = $pdo->prepare("INSERT INTO posts (title, content, image, user_id) VALUES (?, ?, ?, ?)"); $stmt->execute([$title, $content, $imageName, $user_id]); echo "Post created successfully!"; } else { echo "Image upload failed!"; } } ?> <form method="POST" enctype="multipart/form-data"> Title: <input type="text" name="title" required><br><br> Content: <textarea name="content" required></textarea><br><br> Image: <input type="file" name="image" required><br><br> <button type="submit">Create Post</button> </form>

✔ Handles file upload
✔ Stores image name in DB
✔ Uses prepared statements


๐Ÿ“„ 5️⃣ Display Posts (Frontend Integration)

๐Ÿ”น index.php

<?php require 'config.php'; $stmt = $pdo->query("SELECT posts.*, users.name FROM posts JOIN users ON posts.user_id = users.id ORDER BY created_at DESC"); $posts = $stmt->fetchAll(PDO::FETCH_ASSOC); ?> <h2>All Posts</h2> <?php foreach ($posts as $post): ?> <div> <h3><?= htmlspecialchars($post['title']); ?></h3> <p><?= htmlspecialchars($post['content']); ?></p> <p>By: <?= $post['name']; ?></p> <img src="upload/<?= $post['image']; ?>" width="200"> <hr> </div> <?php endforeach; ?>

⚡ 6️⃣ AJAX / Fetch API Example

๐Ÿ”น assets/js/script.js

document.getElementById("loadPosts").addEventListener("click", function() { fetch("fetch_posts.php") .then(response => response.text()) .then(data => { document.getElementById("postContainer").innerHTML = data; }); });

✔ Enables dynamic loading
✔ No page reload required


๐Ÿ“ค 7️⃣ Deployment Options

๐Ÿ–ฅ️ Local Deployment (XAMPP)

  1. Install XAMPP

  2. Place project inside htdocs

  3. Start Apache & MySQL

  4. Open:

    http://localhost/blog_app

๐ŸŒ Shared Hosting Deployment

  1. Purchase hosting (Hostinger / Bluehost / etc.)

  2. Upload files via cPanel File Manager

  3. Create MySQL database in cPanel

  4. Update config.php with live DB credentials


☁️ Cloud Deployment Options

  • VPS (DigitalOcean, AWS EC2)

  • Cloud platforms like:

    • Amazon Web Services

    • Microsoft Azure

    • Google Cloud


๐Ÿ”„ 8️⃣ Version Control Using GitHub

Steps:

git init git add . git commit -m "Initial Blog Project" git branch -M main git remote add origin https://github.com/username/blog-app.git git push -u origin main

Use:

  • GitHub for repository hosting

  • Add .gitignore for:

    upload/ config.php

๐Ÿ” Security Best Practices

✔ Use prepared statements (PDO)
✔ Hash passwords
✔ Validate file uploads (check MIME type & size)
✔ Use htmlspecialchars()
✔ Protect admin routes
✔ Disable error display in production


๐Ÿ“˜ Documentation Should Include

  1. Project Title

  2. Aim

  3. Technologies Used

  4. Database Design

  5. Screenshots

  6. Features

  7. Deployment Steps

  8. Conclusion


๐ŸŽฏ Expected Learning Outcomes

After completing this lab, you can:

  • Build full-stack PHP applications

  • Integrate frontend & backend

  • Use AJAX / Fetch API

  • Handle file uploads

  • Deploy projects

  • Use Git & GitHub

  • Build production-ready web apps








UNIT 1

๐ŸŒ What is Web Development?

Web development is the process of building websites and web applications that run on the internet.
Anything you open in a browser—Google, Instagram, Amazon—is a web app.

At a high level, web development is divided into Frontend, Backend, and Full-Stack.


๐ŸŽจ Frontend Development (Client-Side)

Frontend = what users see and interact with

This is the visual part of a website.

Responsibilities

  • Page layout & design

  • Buttons, forms, animations

  • Responsive design (mobile, tablet, desktop)

  • User interactions (clicks, scrolling, inputs)

Core Technologies

  • HTML – structure (skeleton)

  • CSS – styling (look & feel)

  • JavaScript – interactivity

Popular Frameworks / Libraries

  • React.js

  • Vue.js

  • Angular

  • Tailwind CSS, Bootstrap

Example

  • Login page UI

  • Product listing page

  • Dashboard charts

๐Ÿ‘‰ If you enjoy design, visuals, and UX, frontend is your zone.


⚙️ Backend Development (Server-Side)

Backend = behind the scenes logic

This is where data is processed, stored, and secured.

Responsibilities

  • Business logic

  • Authentication & authorization

  • Database operations

  • APIs for frontend communication

  • Server performance & security

Core Technologies

  • Languages:

    • JavaScript (Node.js)

    • Python (Django, Flask, FastAPI)

    • Java (Spring Boot)

    • PHP (Laravel)

  • Databases:

    • MySQL, PostgreSQL

    • MongoDB

    • Redis

Example

  • Saving user data

  • Processing payments

  • Fetching products from database

๐Ÿ‘‰ If you enjoy logic, data, and problem-solving, backend fits well.


๐Ÿ” Full-Stack Development

Full-Stack = Frontend + Backend

A full-stack developer can build an entire web application end-to-end.

Responsibilities

  • Frontend UI

  • Backend logic

  • Database design

  • API integration

  • Deployment

Common Full-Stack Combos

  • MERN → MongoDB + Express + React + Node.js

  • MEAN → MongoDB + Express + Angular + Node.js

  • Django + React

  • Flask + Vue

Example

  • Building a complete e-commerce website

  • Creating dashboards with login, data, and charts

๐Ÿ‘‰ Best if you want versatility & startup-ready skills.


๐Ÿง  Quick Comparison

AspectFrontendBackendFull-Stack
FocusUI/UXLogic & DataBoth
LanguagesHTML, CSS, JSPython, JS, JavaAll
Database❌✅✅
User FacingYesNoYes
DifficultyMediumMedium–HighHigh



๐Ÿงฉ HTML5 Elements

An HTML element usually consists of:

<tagname> content </tagname>

๐Ÿ”น Common HTML5 Elements

Text & Structure

<h1>Heading</h1> <p>This is a paragraph</p> <span>Inline text</span> <div>Block container</div>

Media

<img src="image.jpg" alt="Image description"> <audio controls src="audio.mp3"></audio> <video controls src="video.mp4"></video>

Lists

<ul> <li>Item 1</li> <li>Item 2</li> </ul> <ol> <li>First</li> <li>Second</li> </ol>

๐Ÿ“ HTML5 Forms

Forms collect user input and send it to the backend.

๐Ÿ”น Basic Form Structure

<form action="/submit" method="POST"> <input type="text" name="username"> <button type="submit">Submit</button> </form>

๐Ÿ”น Common Input Types (HTML5 Superpowers ๐Ÿ’ฅ)

<input type="email" placeholder="Email"> <input type="password" placeholder="Password"> <input type="number" min="1" max="100"> <input type="date"> <input type="file"> <input type="checkbox"> <input type="radio" name="gender">

๐Ÿ”น Useful Form Attributes

  • required – must be filled

  • placeholder – hint text

  • readonly – non-editable

  • disabled – inactive field

  • pattern – regex validation

  • autocomplete – on/off

<input type="text" required pattern="[A-Za-z]+">

๐Ÿ”น Form Validation (No JS!)

HTML5 provides built-in validation:

<input type="email" required>

๐Ÿง  Semantic HTML5 Tags

Semantic tags describe meaning, not just layout.

❌ Non-Semantic

<div class="header"></div> <div class="nav"></div>

✅ Semantic (Recommended)

<header></header> <nav></nav> <main></main> <section></section> <article></article> <aside></aside> <footer></footer>

๐Ÿ”น Common Semantic Tags Explained

TagPurpose
<header>Page or section header
<nav>Navigation links
<main>Main content
<section>Thematic grouping
<article>Independent content
<aside>Sidebar / related info
<footer>Footer info

๐Ÿ”น Example Page Layout

<body> <header> <h1>My Website</h1> </header> <nav> <a href="#">Home</a> <a href="#">About</a> </nav> <main> <section> <article> <h2>Blog Post</h2> <p>Content here...</p> </article> </section> </main> <aside> Ads or links </aside> <footer> © 2026 </footer> </body>

๐ŸŒŸ Why Semantic HTML Matters

  • Better SEO

  • Improved accessibility

  • Cleaner & readable code

  • Easier for screen readers

  • Loved by Google ❤️


๐Ÿš€ Best Practices

✅ Use semantic tags wherever possible
✅ One <main> per page
✅ Use <label> with form inputs

<label for="email">Email</label> <input id="email" type="email">


๐ŸŽฏ CSS3 Selectors

Selectors decide which HTML elements get styled.

๐Ÿ”น Basic Selectors

p { color: blue; } /* element */ #title { font-size: 32px; } /* id */ .card { padding: 16px; } /* class */

๐Ÿ”น Grouping & Universal

h1, h2, h3 { font-family: Arial; } * { margin: 0; padding: 0; }

๐Ÿ”น Combinators

div p { color: red; } /* descendant */ div > p { color: green; } /* direct child */ h1 + p { color: blue; } /* adjacent sibling */

๐Ÿ”น Attribute Selectors

input[type="text"] { border: 1px solid black; }

๐Ÿ”น Pseudo-Classes & Pseudo-Elements

a:hover { color: red; } li:first-child { font-weight: bold; } p::first-letter { font-size: 2em; }

๐Ÿ“ฆ Flexbox (1D Layout King ๐Ÿ‘‘)

Best for rows OR columns.

๐Ÿ”น Container Properties

.container { display: flex; justify-content: space-between; align-items: center; }

๐Ÿ”น Main Flexbox Properties

  • flex-direction → row | column

  • justify-content → main axis

  • align-items → cross axis

  • gap → spacing (use this instead of margins!)

๐Ÿ”น Example

.card-container { display: flex; gap: 20px; }

๐Ÿ‘‰ Use Flexbox for:

  • Navbars

  • Buttons

  • Cards

  • Centering content (finally ๐Ÿ˜Œ)


๐Ÿงฉ CSS Grid (2D Layout Boss ๐Ÿง )

Best for rows AND columns.

๐Ÿ”น Grid Container

.grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; }

๐Ÿ”น Grid Placement

.item1 { grid-column: 1 / 3; }

๐Ÿ”น Layout Example

.page { display: grid; grid-template-areas: "header header" "sidebar main" "footer footer"; } header { grid-area: header; } aside { grid-area: sidebar; } main { grid-area: main; } footer { grid-area: footer; }

๐Ÿ‘‰ Use Grid for:

  • Full-page layouts

  • Dashboards

  • Complex UI sections


๐ŸŽž️ CSS Animations

Make your UI feel alive (not annoying).

๐Ÿ”น Transitions

button { transition: background 0.3s ease; } button:hover { background: black; }

๐Ÿ”น Keyframe Animations

@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } .box { animation: fadeIn 1s ease-in; }

๐Ÿ”น Transform Magic

.card:hover { transform: scale(1.05); }

๐Ÿ“ฑ Responsive Design

Make your site look good on all screens.

๐Ÿ”น Media Queries

@media (max-width: 768px) { .container { flex-direction: column; } }

๐Ÿ”น Responsive Units

  • %

  • vw, vh

  • em, rem

  • clamp() (๐Ÿ”ฅ modern)

h1 { font-size: clamp(1.5rem, 5vw, 3rem); }

๐Ÿ”น Mobile-First Approach (Best Practice)

/* Mobile */ .container { padding: 10px; } /* Desktop */ @media (min-width: 1024px) { .container { padding: 40px; } }

๐Ÿง  Flexbox vs Grid (Quick Rule)

Use CaseChoose
Navbar / buttonsFlexbox
Page layoutGrid
One directionFlexbox
Two directionsGrid


๐Ÿ“ฆ Variables (ES6 Way)

JavaScript has 3 ways to declare variables.

❌ var (old & messy)

var x = 10;

– function-scoped
– can cause bugs
๐Ÿšซ avoid in modern JS

✅ let

let count = 0; count = 1;
  • block-scoped

  • value can change

✅ const

const PI = 3.14;
  • block-scoped

  • cannot be reassigned
    ✔ default choice

Rule of thumb: use const, switch to let only if needed


๐Ÿ”ง Functions

Functions let you reuse logic.

๐Ÿ”น Function Declaration

function greet(name) { return `Hello, ${name}`; }

๐Ÿ”น Arrow Functions (ES6 ⭐)

const greet = (name) => `Hello, ${name}`;

๐Ÿ”น Default Parameters

const add = (a = 0, b = 0) => a + b;

๐Ÿ”น Callback Example

setTimeout(() => { console.log("Hello after 2 seconds"); }, 2000);

๐ŸŒณ DOM Manipulation

DOM = Document Object Model
JavaScript uses DOM to change HTML dynamically.

๐Ÿ”น Selecting Elements

document.getElementById("title"); document.querySelector(".card"); document.querySelectorAll("li");

๐Ÿ”น Changing Content

title.textContent = "New Title"; title.innerHTML = "<span>Hello</span>";

๐Ÿ”น Changing Styles

box.style.backgroundColor = "blue"; box.style.padding = "20px";

๐Ÿ”น Adding / Removing Classes

box.classList.add("active"); box.classList.remove("active"); box.classList.toggle("active");

๐Ÿ”น Creating Elements

const div = document.createElement("div"); div.textContent = "New Element"; document.body.appendChild(div);

๐Ÿ–ฑ️ Events

Events let your page respond to user actions.

๐Ÿ”น Common Events

  • click

  • submit

  • input

  • keydown

  • mouseover

๐Ÿ”น Event Listener

button.addEventListener("click", () => { alert("Button clicked!"); });

๐Ÿ”น Event Object

input.addEventListener("input", (e) => { console.log(e.target.value); });

๐Ÿ”น Prevent Default Behavior

form.addEventListener("submit", (e) => { e.preventDefault(); console.log("Form submitted"); });

๐Ÿ”„ Event Delegation (Pro Move ๐Ÿ˜Ž)

Efficient handling for dynamic elements.

ul.addEventListener("click", (e) => { if (e.target.tagName === "LI") { console.log(e.target.textContent); } });

๐Ÿง  ES6+ Must-Know Extras

// Destructuring const { name, age } = user; // Spread operator const newArr = [...oldArr, 5]; // Template literals console.log(`Hello ${name}`);

๐Ÿš€ Mini Example: Button Counter

<button id="btn">Click</button> <p id="count">0</p> <script> let count = 0; const btn = document.getElementById("btn"); const text = document.getElementById("count"); btn.addEventListener("click", () => { count++; text.textContent = count; }); </script>

✅ Best Practices

✔ Use const by default
✔ Use arrow functions
✔ Avoid inline event handlers
✔ Keep JS logic separate from HTML
✔ Manipulate classes, not inline styles



๐Ÿ“ฆ ES6 Modules

Modules let you split code into reusable files.

๐Ÿ”น Export

// math.js export const add = (a, b) => a + b; export const sub = (a, b) => a - b;

๐Ÿ”น Import

// app.js import { add, sub } from "./math.js";

๐Ÿ”น Default Export

export default function greet() { console.log("Hello"); }
import greet from "./greet.js";

๐Ÿ‘‰ Use modules for scalable codebases.


๐ŸŒ Fetch API (Talking to Servers)

Used to call APIs and get data.

๐Ÿ”น GET Request

fetch("https://api.example.com/users") .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err));

๐Ÿ”น POST Request

fetch("/api/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email, password }) });

๐Ÿ”น Async / Await (Preferred ✅)

const getUsers = async () => { try { const res = await fetch("/api/users"); const data = await res.json(); console.log(data); } catch (err) { console.error(err); } };

⚛️ Introduction to React.js (Optional but Powerful)

React = component-based UI library

Why React?

  • Reusable components

  • Fast updates (Virtual DOM)

  • Industry standard

๐Ÿ”น Basic Component

function Welcome() { return <h1>Hello World</h1>; }

๐Ÿงฉ Components, Props & State

๐Ÿ”น Props (Data from Parent)

function User({ name }) { return <h2>Hello {name}</h2>; }
<User name="Alice" />

๐Ÿ“Œ Props are read-only


๐Ÿ”น State (Dynamic Data)

import { useState } from "react"; function Counter() { const [count, setCount] = useState(0); return ( <button onClick={() => setCount(count + 1)}> {count} </button> ); }

๐Ÿ“Œ State triggers re-render


๐Ÿ–ฑ️ Event Handling & Forms (React Way)

๐Ÿ”น Event Handling

<button onClick={() => alert("Clicked!")}> Click Me </button>

๐Ÿ”น Controlled Form

function Login() { const [email, setEmail] = useState(""); return ( <form> <input value={email} onChange={e => setEmail(e.target.value)} /> </form> ); }

๐Ÿ“Œ React controls form data via state


๐Ÿงญ Routing

๐Ÿ”น React Router (Recommended)

npm install react-router-dom
import { BrowserRouter, Routes, Route } from "react-router-dom"; function App() { return ( <BrowserRouter> <Routes> <Route path="/" element={<Home />} /> <Route path="/login" element={<Login />} /> </Routes> </BrowserRouter> ); }

๐Ÿ”น Plain JavaScript Routing (SPA Style)

window.addEventListener("hashchange", () => { if (location.hash === "#/login") { renderLogin(); } });

๐Ÿ‘‰ React Router is cleaner & scalable.


๐Ÿง  Mental Model (Super Important)

ConceptThink of it as
ComponentReusable UI block
PropsInputs to component
StateInternal memory
FetchData bridge
RouterPage switcher

๐Ÿš€ What You Can Build Now

  • Login & Signup pages

  • Dashboards with API data

  • Single Page Applications

  • Admin panels

  • Your ML / analytics dashboards (perfect for you ๐Ÿ‘€)



UNIT 2

๐Ÿ˜ Introduction to PHP

PHP (Hypertext Preprocessor) is a server-side scripting language mainly used for:

  • Dynamic websites

  • Form handling

  • Database interaction (MySQL)

  • APIs & backend logic

๐Ÿ”น Basic PHP Structure

<?php echo "Hello, World!"; ?>

๐Ÿ“Œ PHP code runs on the server, not in the browser.


๐Ÿงพ PHP Syntax Rules

  • Starts with <?php

  • Ends with ?> (optional in pure PHP files)

  • Statements end with ;

  • Variables start with $

<?php echo "Welcome to PHP";

๐Ÿ“ฆ Variables in PHP

<?php $name = "Alice"; $age = 22; ?>
  • No need to declare data type

  • Case-sensitive ($name ≠ $Name)


๐Ÿ”ข Data Types in PHP

๐Ÿ”น Scalar Types

$string = "Hello"; $int = 10; $float = 5.6; $bool = true;

๐Ÿ”น Compound Types

$array = [1, 2, 3];
$user = [ "name" => "Alice", "age" => 22 ];

๐Ÿ”น Special Types

  • NULL

  • resource

  • object


➗ Operators in PHP

๐Ÿ”น Arithmetic

$a = 10 + 5; $b = 10 * 2;

๐Ÿ”น Assignment

$x += 5;

๐Ÿ”น Comparison

$a == $b; // equal $a === $b; // equal + same type $a != $b;

๐Ÿ”น Logical

$a && $b; $a || $b; !$a;

๐Ÿ”€ Control Structures

๐Ÿ”น if / else

if ($age >= 18) { echo "Adult"; } else { echo "Minor"; }

๐Ÿ”น switch

switch ($day) { case "Mon": echo "Monday"; break; case "Tue": echo "Tuesday"; break; default: echo "Unknown day"; }

๐Ÿ” Loops

๐Ÿ”น for Loop

for ($i = 1; $i <= 5; $i++) { echo $i; }

๐Ÿ”น while Loop

$i = 1; while ($i <= 5) { echo $i; $i++; }

๐Ÿ”น do-while Loop

$i = 1; do { echo $i; $i++; } while ($i <= 5);

๐Ÿ”น foreach (Very Important ⭐)

$colors = ["red", "green", "blue"]; foreach ($colors as $color) { echo $color; }

๐Ÿง  Mini Example

<?php $marks = 75; if ($marks >= 90) { echo "Grade A"; } elseif ($marks >= 60) { echo "Grade B"; } else { echo "Fail"; } ?>

✅ PHP Best Practices (Early Habits)

✔ Use === instead of ==
✔ Always validate user input
✔ Keep logic separate from HTML
✔ Use meaningful variable names



๐Ÿ”ง PHP Functions

Functions let you reuse logic.

๐Ÿ”น Basic Function

<?php function greet($name) { return "Hello, $name"; } echo greet("Alice"); ?>

๐Ÿ”น Default Parameters

function add($a = 0, $b = 0) { return $a + $b; }

๐Ÿ”น Type Hinting (Modern PHP)

function multiply(int $a, int $b): int { return $a * $b; }

๐Ÿ“ฆ Arrays in PHP

๐Ÿ”น Indexed Array

$colors = ["red", "green", "blue"]; echo $colors[0];

๐Ÿ”น Associative Array (Very Important ⭐)

$user = [ "name" => "Alice", "age" => 22 ]; echo $user["name"];

๐Ÿ”น Multidimensional Array

$students = [ ["name" => "A", "marks" => 80], ["name" => "B", "marks" => 70] ];

๐Ÿ”น Looping Arrays

foreach ($user as $key => $value) { echo "$key : $value"; }

๐Ÿ”น Useful Array Functions

count($colors); array_push($colors, "yellow"); array_merge($a, $b); in_array("red", $colors);

๐Ÿ“ Working with Forms in PHP

๐Ÿ”น Basic HTML Form

<form action="submit.php" method="POST"> <input type="text" name="username"> <button type="submit">Submit</button> </form>

๐ŸŒ PHP Superglobals

Superglobals are always available variables.


๐Ÿ”น $_GET

Used to get data from URL.

<a href="page.php?name=Alice">Click</a>
<?php echo $_GET["name"]; ?>

๐Ÿ“Œ Data visible in URL
๐Ÿ“Œ Good for search, filters


๐Ÿ”น $_POST (Most Common)

Used for secure form data.

<?php $username = $_POST["username"]; echo $username; ?>

๐Ÿ“Œ Data not visible in URL
๐Ÿ“Œ Used for login, signup, forms


๐Ÿ”น Input Validation (IMPORTANT ๐Ÿ”)

$username = htmlspecialchars($_POST["username"]);

Always sanitize user input!


๐Ÿ”น $_SESSION

Used to store user data across pages.

Start Session (Required!)

session_start();

Set Session

$_SESSION["user"] = "Alice";

Access Session

echo $_SESSION["user"];

Destroy Session

session_destroy();

๐Ÿ“Œ Used for login systems


๐Ÿช $_COOKIE

Used to store small data on user’s browser.

Set Cookie

setcookie("theme", "dark", time() + 3600);

Get Cookie

echo $_COOKIE["theme"];

๐Ÿ“Œ Cookies have expiry
๐Ÿ“Œ Not secure for sensitive data


๐Ÿง  Mini Example: Login Simulation

<?php session_start(); if ($_POST["email"] === "admin@test.com") { $_SESSION["login"] = true; echo "Logged in"; } else { echo "Invalid login"; } ?>

⚠️ Security Best Practices

๐Ÿšซ Never trust user input
✔ Use htmlspecialchars()
✔ Use password_hash() for passwords
✔ Prefer sessions over cookies
✔ Validate on both frontend & backend


๐Ÿš€ What You Can Build Now

  • Login & logout system

  • Contact forms

  • Dashboard with session auth

  • PHP + MySQL apps

  • Admin panels


๐Ÿ“ PHP File Handling (Read / Write)

๐Ÿ”น Reading Files

Read Entire File

<?php $content = file_get_contents("data.txt"); echo $content; ?>

Read Line by Line

<?php $file = fopen("data.txt", "r"); while (!feof($file)) { echo fgets($file); } fclose($file); ?>

๐Ÿ”น Writing Files

Write / Overwrite

<?php file_put_contents("data.txt", "Hello PHP"); ?>

Append to File

<?php file_put_contents("data.txt", "New Line\n", FILE_APPEND); ?>

๐Ÿ”น File Modes (Important)

ModeDescription
rRead
wWrite (overwrite)
aAppend
r+Read & write

๐Ÿ”น Check File Exists

if (file_exists("data.txt")) { echo "File found"; }

๐Ÿ”น File Upload (Basic)

<form method="POST" enctype="multipart/form-data"> <input type="file" name="file"> <button>Upload</button> </form>
<?php move_uploaded_file( $_FILES["file"]["tmp_name"], "uploads/" . $_FILES["file"]["name"] ); ?>

๐Ÿ“Œ Always validate file type & size!


๐Ÿงฑ Object-Oriented PHP (OOP)

๐Ÿ”น Class & Object

<?php class User { public $name; function setName($name) { $this->name = $name; } } $user = new User(); $user->setName("Alice"); echo $user->name; ?>

๐Ÿ”น Constructor

class User { public $name; function __construct($name) { $this->name = $name; } }

๐Ÿ”น Access Modifiers

class Account { public $id; protected $balance; private $pin; }
ModifierAccess
publicEverywhere
protectedClass + child
privateSame class only

๐Ÿ”น Inheritance

class Admin extends User { public function role() { return "Admin"; } }

๐Ÿ”น Method Overriding

class Admin extends User { function greet() { return "Hello Admin"; } }

๐Ÿ”น Static Methods & Properties

class Math { public static function add($a, $b) { return $a + $b; } } echo Math::add(2, 3);

๐Ÿง  Mini Example: File Logger (OOP)

class Logger { private $file = "log.txt"; public function write($msg) { file_put_contents( $this->file, $msg . "\n", FILE_APPEND ); } } $log = new Logger(); $log->write("User logged in");

⚠️ Best Practices

✔ Close files after use
✔ Validate uploads
✔ Use private properties
✔ Follow single responsibility
✔ Use OOP for scalable apps


๐Ÿš€ What You Can Build Now

  • File-based CMS

  • Log systems

  • Upload managers

  • MVC-style apps

  • Pre-Laravel architecture


๐Ÿšจ Error Handling in PHP

๐Ÿ”น Types of Errors

TypeExample
NoticeUndefined variable
WarningFile not found
FatalCall to undefined function
ExceptionCustom, catchable errors

๐Ÿ”ง Displaying Errors (Development Only!)

ini_set('display_errors', 1); error_reporting(E_ALL);

⚠️ Never enable this in production


❌ Die & Exit (Basic)

if (!file_exists("data.txt")) { die("File not found"); }

✅ Try–Catch (Recommended ⭐)

Used with exceptions.

try { if (!file_exists("data.txt")) { throw new Exception("File missing"); } } catch (Exception $e) { echo $e->getMessage(); }

๐Ÿ” Finally Block

try { // risky code } catch (Exception $e) { echo "Error occurred"; } finally { echo "Cleanup done"; }

๐Ÿง  Custom Exceptions

class MyException extends Exception {} throw new MyException("Custom error");

๐Ÿ“ Error Logging (Production Safe)

error_log("Login failed", 3, "errors.log");

๐Ÿ“Œ Keeps errors hidden from users
๐Ÿ“Œ Essential for debugging live apps


๐Ÿ“ฆ Introduction to Composer

Composer = dependency manager for PHP
(Like npm for JS, pip for Python)

๐Ÿ”น Why Use Composer?

  • Install PHP libraries easily

  • Auto-load classes

  • Manage versions

  • Industry standard


⚙️ Install Composer

composer --version

If not installed → https://getcomposer.org


๐Ÿ“„ composer.json (Heart of Composer)

{ "require": { "monolog/monolog": "^3.0" } }

Install dependencies:

composer install

๐Ÿ”„ Autoloading (Huge Win ๐Ÿš€)

require "vendor/autoload.php";

Now Composer handles all require_once for you.


๐Ÿ“˜ Using a Package (Example: Monolog)

use Monolog\Logger; use Monolog\Handler\StreamHandler; $log = new Logger("app"); $log->pushHandler(new StreamHandler("app.log")); $log->error("Something went wrong");

๐Ÿง  PSR-4 Autoload (Your Own Classes)

"autoload": { "psr-4": { "App\\": "src/" } }
composer dump-autoload
use App\User;

๐Ÿ›ก️ Best Practices

✔ Use try–catch for risky operations
✔ Log errors, don’t echo them
✔ Never expose stack traces in production
✔ Use Composer for all dependencies
✔ Follow PSR standards


๐Ÿš€ What You’re Ready For Now

  • Clean, maintainable PHP apps

  • Real-world backend projects

  • Frameworks like Laravel

  • API development



UNIT 3


๐Ÿ—„️ Introduction to Databases

A database stores data in a structured way so it can be:

  • Inserted

  • Retrieved

  • Updated

  • Deleted
    (aka CRUD)

๐Ÿ”น Why Databases?

  • Faster than files

  • Secure & consistent

  • Handles large data

  • Multi-user access


๐Ÿง  SQL Basics

SQL (Structured Query Language) is used to talk to databases.

๐Ÿ”น Core SQL Commands

CommandPurpose
CREATECreate tables/databases
INSERTAdd data
SELECTFetch data
UPDATEModify data
DELETERemove data

๐Ÿ—️ MySQL / MariaDB Basics

MariaDB is a drop-in replacement for MySQL (same syntax).

๐Ÿ”น Create Database

CREATE DATABASE school; USE school;

๐Ÿ“‹ Tables

A table = rows + columns.

๐Ÿ”น Create Table

CREATE TABLE students ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), email VARCHAR(100) UNIQUE, age INT );

๐Ÿ”น Insert Data

INSERT INTO students (name, email, age) VALUES ("Alice", "alice@mail.com", 22);

๐Ÿ”น Select Data

SELECT * FROM students; SELECT name, age FROM students;

๐Ÿ”น Update Data

UPDATE students SET age = 23 WHERE id = 1;

⚠️ Always use WHERE with UPDATE!


๐Ÿ”น Delete Data

DELETE FROM students WHERE id = 1;

๐Ÿ”— Relationships in Databases

Relationships connect tables using keys.

๐Ÿ”น Primary Key

id INT PRIMARY KEY

๐Ÿ”น Foreign Key

student_id INT, FOREIGN KEY (student_id) REFERENCES students(id)

๐Ÿ”น One-to-Many (Most Common)

Example: One student → many enrollments

CREATE TABLE enrollments ( id INT AUTO_INCREMENT PRIMARY KEY, student_id INT, course VARCHAR(100), FOREIGN KEY (student_id) REFERENCES students(id) );

๐Ÿ”€ SQL Joins (VERY IMPORTANT ⭐)

๐Ÿ”น INNER JOIN

Returns matching rows only.

SELECT students.name, enrollments.course FROM students INNER JOIN enrollments ON students.id = enrollments.student_id;

๐Ÿ”น LEFT JOIN

Returns all rows from left table.

SELECT students.name, enrollments.course FROM students LEFT JOIN enrollments ON students.id = enrollments.student_id;

๐Ÿ”น RIGHT JOIN

Returns all rows from right table.

SELECT students.name, enrollments.course FROM students RIGHT JOIN enrollments ON students.id = enrollments.student_id;

๐Ÿง  Visual Join Intuition

  • INNER JOIN → intersection

  • LEFT JOIN → left + match

  • RIGHT JOIN → right + match


⚡ Useful SQL Extras

WHERE age > 18 ORDER BY name ASC LIMIT 10 COUNT(*)

๐Ÿง  Mini Real-World Example

SELECT s.name, COUNT(e.id) AS courses FROM students s LEFT JOIN enrollments e ON s.id = e.student_id GROUP BY s.name;

๐Ÿ›ก️ Best Practices

✔ Use primary keys
✔ Normalize data
✔ Use foreign keys
✔ Avoid SELECT * in production
✔ Index frequently searched columns


๐Ÿš€ What You’re Ready For Now

  • PHP + MySQL integration

  • Login systems

  • CRUD applications

  • APIs with relational data



๐Ÿ” CRUD Operations in SQL

CRUD = Create, Read, Update, Delete

Assume this table:

CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), email VARCHAR(100) UNIQUE, password VARCHAR(255) );

๐ŸŸข CREATE (INSERT)

INSERT INTO users (name, email, password) VALUES ('Alice', 'alice@mail.com', 'hashed_pwd');

๐Ÿ”ต READ (SELECT)

SELECT * FROM users;

With condition:

SELECT name, email FROM users WHERE id = 1;

๐ŸŸก UPDATE

UPDATE users SET name = 'Alice Smith' WHERE id = 1;

⚠️ Never update without WHERE


๐Ÿ”ด DELETE

DELETE FROM users WHERE id = 1;

๐Ÿง  CRUD Summary

OperationSQL
CreateINSERT
ReadSELECT
UpdateUPDATE
DeleteDELETE

๐Ÿ”— Connecting PHP with MySQL

You have two options:

  • mysqli (procedural / OOP)

  • PDO (recommended ⭐)


๐ŸŸฆ Option 1: mysqli (Procedural)

๐Ÿ”น Connect

$conn = mysqli_connect("localhost", "root", "", "test_db"); if (!$conn) { die("Connection failed"); }

๐Ÿ”น INSERT

$sql = "INSERT INTO users (name, email) VALUES ('Bob', 'bob@mail.com')"; mysqli_query($conn, $sql);

๐Ÿ”น SELECT

$result = mysqli_query($conn, "SELECT * FROM users"); while ($row = mysqli_fetch_assoc($result)) { echo $row["name"]; }

๐ŸŸฆ Option 2: PDO (BEST PRACTICE ⭐)

๐Ÿ”น Connect Using PDO

try { $pdo = new PDO( "mysql:host=localhost;dbname=test_db", "root", "" ); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { die($e->getMessage()); }

๐Ÿ” Prepared Statements (SECURITY ๐Ÿ”’)

๐Ÿ”น INSERT (Safe)

$stmt = $pdo->prepare( "INSERT INTO users (name, email) VALUES (?, ?)" ); $stmt->execute(["Alice", "alice@mail.com"]);

๐Ÿ”น SELECT

$stmt = $pdo->prepare("SELECT * FROM users"); $stmt->execute(); $users = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach ($users as $user) { echo $user["name"]; }

๐Ÿ”น UPDATE

$stmt = $pdo->prepare( "UPDATE users SET name=? WHERE id=?" ); $stmt->execute(["New Name", 1]);

๐Ÿ”น DELETE

$stmt = $pdo->prepare("DELETE FROM users WHERE id=?"); $stmt->execute([1]);

๐Ÿง  Why PDO > mysqli?

FeaturePDOmysqli
Prepared statements✅✅
Multiple DBs✅❌
Named parameters✅❌
Cleaner syntax✅❌

๐Ÿ›ก️ Security Musts

✔ Always use prepared statements
✔ Never store plain passwords

password_hash($pwd, PASSWORD_BCRYPT);

✔ Validate user input
✔ Use try–catch for DB errors


๐Ÿš€ Mini Flow (Real App)

  1. HTML Form

  2. PHP receives $_POST

  3. PHP validates data

  4. PDO inserts into MySQL

  5. Success response


๐Ÿ”ฅ What You Can Build Now

  • User authentication

  • Admin dashboards

  • CRUD apps

  • APIs

  • CMS systems



๐Ÿ” Data Validation & Sanitization (Prevent SQL Injection)

๐Ÿงจ What is SQL Injection?

When attackers inject SQL into inputs:

' OR 1=1 --

…and suddenly your whole table is exposed ๐Ÿ˜ฌ


✅ Rule #1: NEVER trust user input

Frontend validation is nice.
Backend validation is mandatory.


๐Ÿงผ Sanitization (Cleaning Input)

๐Ÿ”น Basic Sanitization

$name = htmlspecialchars(trim($_POST["name"]));

๐Ÿ”น Filter Functions (Recommended)

$email = filter_input(INPUT_POST, "email", FILTER_SANITIZE_EMAIL);

✔️ Validation (Check Correctness)

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { die("Invalid email"); }

Other examples:

is_numeric($age); strlen($password) >= 8;

๐Ÿ” SQL Injection Protection (MOST IMPORTANT ⭐)

❌ WRONG (Vulnerable)

$sql = "SELECT * FROM users WHERE email='$email'";

✅ RIGHT (Prepared Statements)

$stmt = $pdo->prepare( "SELECT * FROM users WHERE email = ?" ); $stmt->execute([$email]);

๐Ÿ“Œ Prepared statements separate SQL from data


๐Ÿ”‘ Authentication System (Login & Signup)

๐Ÿ”น Password Hashing (NEVER store plain text)

$hashed = password_hash($password, PASSWORD_BCRYPT);

๐Ÿ”น Verify Password

if (password_verify($password, $row["password"])) { echo "Login success"; }

๐Ÿงพ Signup Flow

  1. Validate input

  2. Hash password

  3. Store in DB

$stmt = $pdo->prepare( "INSERT INTO users (email, password) VALUES (?, ?)" ); $stmt->execute([$email, $hashed]);

๐Ÿ” Login Flow

$stmt = $pdo->prepare( "SELECT * FROM users WHERE email = ?" ); $stmt->execute([$email]); $user = $stmt->fetch(); if ($user && password_verify($password, $user["password"])) { session_start(); $_SESSION["user_id"] = $user["id"]; }

๐Ÿง  Session Management

๐Ÿ”น Start Session

session_start();

๐Ÿ”น Set Session

$_SESSION["user"] = "Alice";

๐Ÿ”น Check Auth (Protect Pages)

if (!isset($_SESSION["user"])) { header("Location: login.php"); exit; }

๐Ÿ”น Logout

session_start(); session_destroy();

๐Ÿ›ก️ Session Security Best Practices

✔ Regenerate session ID on login

session_regenerate_id(true);

✔ Use HTTPS
✔ Set session timeout
✔ Never store passwords in session


๐Ÿช Cookies vs Sessions

FeatureCookieSession
Stored onBrowserServer
Secure❌✅
Use for auth❌✅

๐ŸŒฑ Optional: Introduction to NoSQL (MongoDB)

๐Ÿง  What is NoSQL?

  • Schema-less

  • JSON-like documents

  • Flexible structure

  • Scales horizontally

๐Ÿ“Œ Use when data structure changes often.


๐Ÿ“ฆ MongoDB vs MySQL

FeatureMongoDBMySQL
SchemaFlexibleFixed
JoinsLimitedStrong
StructureJSONTables
Use casesLogs, analyticsTransactions

๐Ÿ”— Connecting MongoDB with PHP

๐Ÿ”น Install MongoDB Driver

composer require mongodb/mongodb

๐Ÿ”น Connect to MongoDB

require "vendor/autoload.php"; $client = new MongoDB\Client("mongodb://localhost:27017"); $collection = $client->test->users;

๐Ÿ”น Insert Document

$collection->insertOne([ "name" => "Alice", "email" => "alice@mail.com" ]);

๐Ÿ”น Fetch Documents

$users = $collection->find(); foreach ($users as $user) { echo $user["name"]; }

๐Ÿง  When to Use What?

  • Auth, payments, CRUD → MySQL

  • Logs, ML data, flexible data → MongoDB

  • Hybrid apps → both (very common)


๐Ÿš€ What You’re Fully Capable of Now

  • Secure login systems

  • Role-based access

  • Admin dashboards

  • REST APIs

  • Full backend for React apps



UNIT 4


๐Ÿ”— How Frontend Talks to PHP Backend

Flow looks like this:

HTML / JS ↓ (Fetch / AJAX) PHP Script ↓ Database ↓ JSON Response

๐Ÿ“Œ No page reload
๐Ÿ“Œ Smooth UX (SPA-like)


๐Ÿงฑ Backend Rule (Very Important)

Your PHP backend should return JSON, not HTML.

header("Content-Type: application/json");

๐ŸŒ Using Fetch API (Modern Way ⭐)

๐Ÿ”น Frontend (GET Request)

<button id="load">Load Users</button> <ul id="list"></ul> <script> document.getElementById("load").addEventListener("click", async () => { const res = await fetch("users.php"); const data = await res.json(); document.getElementById("list").innerHTML = data.map(u => `<li>${u.name}</li>`).join(""); }); </script>

๐Ÿ”น Backend (users.php)

<?php header("Content-Type: application/json"); echo json_encode([ ["name" => "Alice"], ["name" => "Bob"] ]);

๐Ÿ“ค POST Request (Forms Without Reload)

๐Ÿ”น Frontend

<form id="loginForm"> <input name="email"> <input name="password" type="password"> <button>Login</button> </form> <script> document.getElementById("loginForm").addEventListener("submit", async e => { e.preventDefault(); const formData = new FormData(e.target); const res = await fetch("login.php", { method: "POST", body: formData }); const result = await res.json(); alert(result.message); }); </script>

๐Ÿ”น Backend (login.php)

<?php header("Content-Type: application/json"); if ($_POST["email"] === "admin@test.com") { echo json_encode(["status" => "success", "message" => "Logged in"]); } else { echo json_encode(["status" => "error", "message" => "Invalid login"]); }

๐Ÿ“ฆ Sending JSON Instead of FormData

fetch("api.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email, password }) });
$data = json_decode(file_get_contents("php://input"), true);

⏳ AJAX with XMLHttpRequest (Old but Useful)

const xhr = new XMLHttpRequest(); xhr.open("GET", "data.php"); xhr.onload = () => { console.log(JSON.parse(xhr.responseText)); }; xhr.send();

๐Ÿ“Œ Fetch is preferred in modern apps.


๐Ÿ” Sessions + Fetch (Auth)

Sessions still work automatically if:

  • Same domain

  • Cookies enabled

session_start(); $_SESSION["user"] = "Alice";
fetch("dashboard.php");

๐Ÿง  Common Use Cases

  • Login & Signup

  • Live search

  • Pagination

  • Form validation

  • Dashboards

  • API-based apps


⚠️ Common Mistakes

❌ Echo HTML instead of JSON
❌ Forget header("Content-Type: application/json")
❌ Not handling errors
❌ Exposing sensitive data


✅ Best Practices

✔ Always return JSON
✔ Use async/await
✔ Validate data in PHP
✔ Handle errors gracefully
✔ Separate frontend & backend folders


๐Ÿš€ Mini Architecture (Clean Setup)

/frontend index.html app.js /backend login.php users.php db.php

๐Ÿ”ฅ What You Can Build Now

  • SPA-style apps

  • React frontend + PHP backend

  • Admin panels

  • APIs for mobile apps

  • Secure dashboards


๐ŸŒ RESTful API Basics using PHP

๐Ÿง  What is a REST API?

REST (Representational State Transfer) is a way for systems to communicate over HTTP using standard methods.

Instead of pages → you send & receive JSON.


๐Ÿ” HTTP Methods (Core of REST)

MethodPurpose
GETRead data
POSTCreate data
PUTUpdate data
DELETEDelete data

๐Ÿ“ฆ REST API Rules (Simple)

✔ Use URLs as resources
✔ Use HTTP methods, not verbs in URLs
✔ Return JSON only
✔ Use proper status codes


๐Ÿ“‚ Example Resource

/api/users /api/users/1

๐Ÿงฑ Basic PHP API Structure

<?php header("Content-Type: application/json"); header("Access-Control-Allow-Origin: *"); $method = $_SERVER["REQUEST_METHOD"];

๐Ÿ”ต GET – Fetch Data

if ($method === "GET") { echo json_encode([ ["id" => 1, "name" => "Alice"], ["id" => 2, "name" => "Bob"] ]); }

๐ŸŸข POST – Create Data

$data = json_decode(file_get_contents("php://input"), true); if ($method === "POST") { echo json_encode([ "status" => "success", "name" => $data["name"] ]); }

๐ŸŸก PUT – Update Data

if ($method === "PUT") { parse_str(file_get_contents("php://input"), $data); echo json_encode(["updated" => true]); }

๐Ÿ”ด DELETE – Remove Data

if ($method === "DELETE") { echo json_encode(["deleted" => true]); }

๐Ÿ“ก HTTP Status Codes (IMPORTANT ⭐)

http_response_code(201); // Created http_response_code(400); // Bad Request http_response_code(401); // Unauthorized http_response_code(404); // Not Found http_response_code(500); // Server Error

๐Ÿง  Example: RESTful Users API (Clean)

switch ($method) { case "GET": // fetch users break; case "POST": // create user break; case "PUT": // update user break; case "DELETE": // delete user break; }

๐Ÿ” API Best Practices

✔ Validate input
✔ Use prepared statements
✔ Return consistent JSON
✔ Never expose DB errors
✔ Use tokens (JWT) for auth


๐Ÿ“ File Uploads & Media Management

๐Ÿง  How File Upload Works

Frontend Form ↓ $_FILES ↓ Server Validation ↓ Upload Directory ↓ DB (store filename/path)

๐Ÿ“ค HTML Upload Form

<form method="POST" enctype="multipart/form-data"> <input type="file" name="image"> <button>Upload</button> </form>

๐Ÿ“ฆ PHP File Upload Handling

$file = $_FILES["image"]; move_uploaded_file( $file["tmp_name"], "uploads/" . $file["name"] );

๐Ÿ” File Validation (CRITICAL ๐Ÿ”ฅ)

✔ Check File Type

$allowed = ["image/jpeg", "image/png"]; if (!in_array($file["type"], $allowed)) { die("Invalid file type"); }

✔ Check File Size

if ($file["size"] > 2 * 1024 * 1024) { die("File too large"); }

✔ Rename Files (Avoid Overwrites)

$filename = uniqid() . "_" . basename($file["name"]);

๐Ÿ—‚️ Store File Info in Database

CREATE TABLE uploads ( id INT AUTO_INCREMENT PRIMARY KEY, filename VARCHAR(255), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
$stmt = $pdo->prepare( "INSERT INTO uploads (filename) VALUES (?)" ); $stmt->execute([$filename]);

๐Ÿ“ธ Fetch Uploaded Media

$files = glob("uploads/*"); foreach ($files as $file) { echo "<img src='$file' width='100'>"; }

๐Ÿ›ก️ Upload Security Checklist

๐Ÿšซ Never trust filename
✔ Validate MIME type
✔ Limit file size
✔ Use uniqid()
✔ Block executable uploads
✔ Store uploads outside root (best)


๐Ÿš€ What You Can Build Now

  • REST APIs for frontend/mobile

  • Image upload systems

  • Profile picture uploads

  • CMS media managers

  • Admin dashboards

  • React + PHP API backend


๐Ÿ” Security Best Practices in PHP

๐Ÿง  Core Security Rule

Never trust user input. Ever.

Assume everything coming from:

  • Forms

  • URLs

  • Cookies

  • Headers

  • APIs
    is malicious until proven otherwise.


๐Ÿงผ Data Sanitization & Validation

✔ Validation (Is data correct?)

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { die("Invalid email"); }

✔ Sanitization (Clean unsafe characters)

$email = filter_input(INPUT_POST, "email", FILTER_SANITIZE_EMAIL);

๐Ÿšซ Prevent SQL Injection (CRITICAL ๐Ÿ”ฅ)

❌ Vulnerable Code

$sql = "SELECT * FROM users WHERE email='$email'";

✅ Secure Code (Prepared Statements)

$stmt = $pdo->prepare( "SELECT * FROM users WHERE email = ?" ); $stmt->execute([$email]);

✔ This alone stops 90% of attacks


๐Ÿช Secure Cookies

❌ Insecure Cookie

setcookie("user", $id);

✅ Secure Cookie

setcookie("user", $id, [ "expires" => time() + 3600, "httponly" => true, "secure" => true, "samesite" => "Strict" ]);

๐Ÿ” Cookie Flags Explained

FlagPurpose
HttpOnlyBlocks JS access
SecureHTTPS only
SameSitePrevents CSRF

๐Ÿง  Session Security

✔ Start Session Securely

session_start([ "use_strict_mode" => 1, "cookie_httponly" => 1, "cookie_secure" => 1 ]);

๐Ÿ”„ Regenerate Session ID (IMPORTANT)

session_regenerate_id(true);

Use after login to prevent session hijacking.


⏳ Session Timeout

if (isset($_SESSION["last_activity"]) && time() - $_SESSION["last_activity"] > 1800) { session_destroy(); } $_SESSION["last_activity"] = time();

๐Ÿ›‘ CSRF Protection

✔ CSRF Token

$_SESSION["token"] = bin2hex(random_bytes(32));

✔ In Form

<input type="hidden" name="token" value="<?= $_SESSION['token'] ?>">

✔ Validate

if ($_POST["token"] !== $_SESSION["token"]) { die("CSRF detected"); }

๐Ÿงช XSS Protection

❌ Vulnerable Output

echo $_GET["name"];

✅ Safe Output

echo htmlspecialchars($_GET["name"], ENT_QUOTES, "UTF-8");

๐Ÿ” Password Security

✔ Hash Passwords

$hash = password_hash($password, PASSWORD_DEFAULT);

✔ Verify

password_verify($password, $hash);

๐Ÿšซ Never use MD5 or SHA1.


๐Ÿšซ Disable Dangerous PHP Settings

display_errors = Off allow_url_include = Off expose_php = Off

๐Ÿ” File Upload Security (Recap)

✔ MIME type check
✔ Size limit
✔ Rename files
✔ No .php uploads
✔ Store outside web root


๐Ÿš€ Deployment: Hosting PHP Applications

๐Ÿ–ฅ️ Local Development (XAMPP / LAMP)

✔ XAMPP (Windows / macOS)

  • Apache

  • MySQL

  • PHP

  • phpMyAdmin

๐Ÿ“‚ Project folder:

htdocs/your_project/

Access:

http://localhost/your_project

✔ LAMP (Linux)

sudo apt install apache2 mysql-server php

Project path:

/var/www/html/

๐ŸŒ Shared Hosting (Beginner Friendly)

Examples

  • Bluehost

  • Hostinger

  • GoDaddy

How It Works

  1. Upload files to public_html

  2. Create DB via cPanel

  3. Update config.php

  4. Done ✅

✔ Cheap
❌ Limited control


☁️ Cloud Hosting (Professional Level)

Popular Choices

  • AWS EC2

  • DigitalOcean

  • Linode

  • Vultr


๐Ÿงฑ Typical Cloud Stack

Nginx / Apache PHP-FPM MySQL / MariaDB Ubuntu Server

๐Ÿš€ Deploy PHP App on Cloud (High Level)

  1. Create server (Ubuntu)

  2. Install LEMP/LAMP

  3. Upload code (Git / SCP)

  4. Set permissions

  5. Configure .env

  6. Enable HTTPS (Let’s Encrypt)

  7. Done ๐ŸŽ‰


๐Ÿ” Environment Variables (.env)

DB_HOST=localhost DB_NAME=app_db DB_USER=root DB_PASS=secret

Load with:

$_ENV["DB_NAME"];

๐Ÿšซ Never commit secrets to Git.


๐Ÿ”’ HTTPS (Mandatory)

sudo certbot --nginx

✔ Encrypts cookies
✔ Protects sessions
✔ Required for Secure flag


๐Ÿงช Deployment Checklist

✅ Error reporting OFF
✅ HTTPS enabled
✅ File permissions correct
✅ .env secured
✅ DB access limited
✅ Backups enabled


๐ŸŽฏ What You’re Ready For Now

  • Secure login systems

  • Production REST APIs

  • Hosting real apps

  • Handling real users

  • Moving to Laravel effortlessly


๐Ÿง  Version Control with Git & GitHub

❓ Why Git Matters

Without Git:

  • No collaboration

  • No history

  • No rollback

  • No professionalism

With Git:
✔ Track changes
✔ Collaborate safely
✔ Deploy easily
✔ Showcase work (GitHub)


๐Ÿ› ️ Git Basics (Core Commands)

๐Ÿ”น Initialize a Repo

git init

๐Ÿ”น Check Status

git status

๐Ÿ”น Add Files

git add .

๐Ÿ”น Commit Changes

git commit -m "Initial commit"

✔ Commit message should explain what changed


๐ŸŒฟ Branching (IMPORTANT)

git branch feature-login git checkout feature-login

Or (shortcut):

git checkout -b feature-login

Why branches?

  • Work on features safely

  • Avoid breaking main code


๐Ÿ”€ Merge Branch

git checkout main git merge feature-login

๐ŸŒ GitHub Workflow

๐Ÿ”น Push to GitHub

git remote add origin https://github.com/user/repo.git git push -u origin main

๐Ÿ”น Pull Latest Changes

git pull origin main

๐Ÿšซ .gitignore (CRITICAL ๐Ÿ”ฅ)

Never commit:

  • Config files

  • Secrets

  • Vendor files

Example .gitignore

.env /vendor /node_modules /uploads

๐Ÿท️ Common Git Mistakes

❌ Committing secrets
❌ Huge commits
❌ No branches
❌ No commit messages


๐Ÿง  Professional Git Habits

✔ Small commits
✔ Descriptive messages
✔ Feature branches
✔ README.md
✔ Issues & Projects


๐Ÿ“˜ README.md Structure

# Project Name ## Features ## Tech Stack ## Setup Instructions ## Screenshots

⚛️ Integrating Frontend Framework with PHP Backend

You’re moving into decoupled architecture now ๐Ÿ”ฅ


๐Ÿง  How Modern Stack Works

React / Vue (Frontend) ↓ API Calls (JSON) PHP REST API (Backend) ↓ Database

✔ Frontend = UI
✔ Backend = Logic + DB
✔ Communication = REST API


๐Ÿ”Œ Backend (PHP API Example)

header("Content-Type: application/json"); header("Access-Control-Allow-Origin: *"); echo json_encode([ "message" => "Hello from PHP API" ]);

๐ŸŒ CORS (IMPORTANT)

header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE"); header("Access-Control-Allow-Headers: Content-Type");

⚛️ React → PHP API (Fetch Example)

fetch("http://localhost/api/users.php") .then(res => res.json()) .then(data => console.log(data));

๐Ÿง  React Component Example

import { useEffect, useState } from "react"; function Users() { const [users, setUsers] = useState([]); useEffect(() => { fetch("http://localhost/api/users.php") .then(res => res.json()) .then(setUsers); }, []); return ( <ul> {users.map(u => ( <li key={u.id}>{u.name}</li> ))} </ul> ); } export default Users;

๐Ÿงพ POST Data from React to PHP

fetch("http://localhost/api/create-user.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "Alice" }) });
$data = json_decode(file_get_contents("php://input"), true);

๐Ÿ” Authentication with React + PHP

Options:

  • Sessions (same domain)

  • JWT (recommended)

JWT Flow

Login → Token → LocalStorage → API Headers
Authorization: Bearer TOKEN

๐Ÿงช Development Setup (Recommended)

FrontendBackend
localhost:3000localhost:8000
Vite / CRAApache / PHP

๐Ÿš€ Production Setup

✔ Build frontend
✔ Upload /dist
✔ API on /api
✔ Enable HTTPS
✔ Secure CORS


๐Ÿง  Vue + PHP (Same Idea)

axios.get("/api/users")

Framework doesn’t matter — API contract does.


๐ŸŽฏ Real Projects You Can Build Now

  • React + PHP blog

  • Auth system with JWT

  • Admin dashboard

  • File upload manager

  • E-commerce backend

  • REST API for mobile apps


๐Ÿ”ฅ Perfect Capstone Project (Highly Recommended)

Full-Stack App

  • React frontend

  • PHP REST API

  • MySQL DB

  • JWT auth

  • File uploads

  • Role-based access

  • GitHub repo

  • Live deployment






2 comments:

02

Capstone resource hub

Codingacharya

Capstone Learning Resources, Notes & Project Hub

TCS NQT Questions
Read Notes
Machine Learning – ACE Theory
Read Notes
Machine Learning PPT
Read Notes
MachienLearning LAB
Read Notes
CSPT LAB programs
Read Notes
Time table and CSPT syllabus
Read Notes
Appreciations
Read Notes
ISTE life memberships
Read Notes
Artificial Intelligence & Analytics
Read Notes
Fullstack Web Dev
Read Notes
MERN Web Dev
Read Notes
Course Structure
Read Notes
Cloud Computing
Read Notes
90 Days ML Challenge
Read Notes
Advanced Analytics & Viz
Read Notes
Advanced Machine Learning
Read Notes
React JS
Read Notes
ML Chaitanya
Read Notes
Important Links
Read Notes
CSS Effects
Read Notes
RESUME
Read Notes
Bootstrap CSS
Read Notes
MongoDB
Read Notes
OWN Python Package
Read Notes
HTML Course
Read Notes
HTML Projects
Read Notes
GitHub Projects
Read Notes
Angular JS
Read Notes
Journals
Read Notes
NLP Notes
Read Notes
Videos
Read Notes
Data Analytics & Viz
Read Notes
Cloud Computing (Archive)
Read Notes
Open CV
Read Notes
jQuery
Read Notes
React JS (Archive)
Read Notes
Node JS
Read Notes
DAV Theory
Read Notes
DAV Lab
Read Notes
Big Data Notes
Read Notes
R-Programming
Read Notes
HADOOP Lab
Read Notes
GATE DA
Read Notes
JAVA Lab
Read Notes
Computer Networks
Read Notes
03

Live projects & profiles