Category: Courses

Courses

  • Lesson 14: CRUD Operations in PHP

    CRUD stands for Create, Read, Update, and Delete, the fundamental operations of managing data in a database. This lesson will guide you through implementing these operations in PHP using MySQL.


    Lesson Outline

    1. Introduction to CRUD Operations
    2. Setting Up the Environment
    3. Creating Data (INSERT)
    4. Reading Data (SELECT)
    5. Updating Data (UPDATE)
    6. Deleting Data (DELETE)
    7. Practical CRUD Example with a “Users” Table
    8. Activities and Assignments

    14.1 Introduction to CRUD Operations

    What are CRUD Operations?

    CRUD operations form the core functionality of any database-driven application:

    • Create: Add new records to the database.
    • Read: Retrieve and display data from the database.
    • Update: Modify existing records.
    • Delete: Remove records from the database.

    14.2 Setting Up the Environment

    Step 1: Database Setup

    Create a database crud_demo with a users table:

    sql

    CREATE DATABASE crud_demo;

    USE crud_demo;

    CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    );

    Step 2: Insert Sample Data

    sql
    INSERT INTO users (name, email) VALUES
    ('Alice', 'alice@example.com'),
    ('Bob', 'bob@example.com');

    Step 3: Connection Script

    Create a file db.php for reusable database connection code:

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


    14.3 Creating Data (INSERT)

    Insert Operation

    Use the INSERT INTO SQL statement to add new records.

    Example: Insert User

    Create a file create.php:

    php
    <?php
    require 'db.php';
    if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
    $name = $_POST[‘name’];
    $email = $_POST[’email’];

    $stmt = $conn->prepare(“INSERT INTO users (name, email) VALUES (:name, :email)”);
    $stmt->bindParam(‘:name’, $name);
    $stmt->bindParam(‘:email’, $email);

    if ($stmt->execute()) {
    echo “User added successfully!”;
    } else {
    echo “Error adding user.”;
    }
    }
    ?>

    <form method=“POST” action=“”>
    Name: <input type=“text” name=“name” required><br>
    Email: <input type=“email” name=“email” required><br>
    <button type=“submit”>Add User</button>
    </form>


    14.4 Reading Data (SELECT)

    Read Operation

    Use the SELECT SQL statement to retrieve data.

    Example: Display Users

    Create a file read.php:

    php
    <?php
    require 'db.php';
    $stmt = $conn->query(“SELECT * FROM users”);
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    ?>

    <table border=“1”>
    <tr>
    <th>ID</th>
    <th>Name</th>
    <th>Email</th>
    <th>Created At</th>
    </tr>
    <?php foreach ($users as $user): ?>
    <tr>
    <td><?= $user[‘id’]; ?></td>
    <td><?= $user[‘name’]; ?></td>
    <td><?= $user[’email’]; ?></td>
    <td><?= $user[‘created_at’]; ?></td>
    </tr>
    <?php endforeach; ?>
    </table>


    14.5 Updating Data (UPDATE)

    Update Operation

    Use the UPDATE SQL statement to modify existing records.

    Example: Update User

    Create a file update.php:

    php
    <?php
    require 'db.php';
    if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
    $id = $_POST[‘id’];
    $name = $_POST[‘name’];
    $email = $_POST[’email’];

    $stmt = $conn->prepare(“UPDATE users SET name = :name, email = :email WHERE id = :id”);
    $stmt->bindParam(‘:id’, $id);
    $stmt->bindParam(‘:name’, $name);
    $stmt->bindParam(‘:email’, $email);

    if ($stmt->execute()) {
    echo “User updated successfully!”;
    } else {
    echo “Error updating user.”;
    }
    }

    // Fetch the user details for editing
    $id = $_GET[‘id’];
    $stmt = $conn->prepare(“SELECT * FROM users WHERE id = :id”);
    $stmt->bindParam(‘:id’, $id);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    ?>

    <form method=“POST” action=“”>
    <input type=“hidden” name=“id” value=“<?= $user[‘id’]; ?>”>
    Name: <input type=“text” name=“name” value=“<?= $user[‘name’]; ?>” required><br>
    Email: <input type=“email” name=“email” value=“<?= $user[’email’]; ?>” required><br>
    <button type=“submit”>Update User</button>
    </form>


    14.6 Deleting Data (DELETE)

    Delete Operation

    Use the DELETE SQL statement to remove records.

    Example: Delete User

    Create a file delete.php:

    php
    <?php
    require 'db.php';
    if ($_SERVER[“REQUEST_METHOD”] == “GET” && isset($_GET[‘id’])) {
    $id = $_GET[‘id’];

    $stmt = $conn->prepare(“DELETE FROM users WHERE id = :id”);
    $stmt->bindParam(‘:id’, $id);

    if ($stmt->execute()) {
    echo “User deleted successfully!”;
    } else {
    echo “Error deleting user.”;
    }
    }
    ?>


    14.7 Practical CRUD Example

    Create a file index.php that ties all operations together:

    php
    <?php
    require 'db.php';
    $stmt = $conn->query(“SELECT * FROM users”);
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    ?>

    <a href=“create.php”>Add User</a>
    <table border=“1”>
    <tr>
    <th>ID</th>
    <th>Name</th>
    <th>Email</th>
    <th>Actions</th>
    </tr>
    <?php foreach ($users as $user): ?>
    <tr>
    <td><?= $user[‘id’]; ?></td>
    <td><?= $user[‘name’]; ?></td>
    <td><?= $user[’email’]; ?></td>
    <td>
    <a href=“update.php?id=<?= $user[‘id’]; ?>”>Edit</a>
    <a href=“delete.php?id=<?= $user[‘id’]; ?>” onclick=“return confirm(‘Are you sure?’)”>Delete</a>
    </td>
    </tr>
    <?php endforeach; ?>
    </table>


    Activities and Exercises

    1. Create a Products Table:
      • Columns: id, name, price, quantity, created_at.
      • Implement CRUD operations for managing products.
    2. User Management:
      • Add functionality to search users by name or email.
    3. Validation:
      • Add validation to ensure that all fields are filled before inserting or updating data.

    Assignment

    1. Create a tasks table with the following columns:
      • id (Primary Key)
      • task_name (VARCHAR)
      • status (ENUM: pending, completed)
    2. Build a CRUD application:
      • Create tasks.
      • Display all tasks.
      • Update the status of tasks.
      • Delete tasks.

    Summary

    In this lesson, you learned:

    1. How to perform CRUD operations using PHP and MySQL.
    2. The importance of using prepared statements for secure database interactions.
    3. How to tie together Create, Read, Update, and Delete operations in a dynamic web application.

    These skills are essential for developing database-driven applications. Let me know if you need additional guidance!

  • Lesson 13: Introduction to MySQL

    Databases are essential for dynamic web applications. MySQL is one of the most popular relational database management systems (RDBMS) used with PHP. In this lesson, you will learn how to set up a MySQL database and connect it to PHP using PDO and MySQLi.


    13.1 Setting Up a Database

    What is MySQL?

    • MySQL: An open-source relational database system for managing data.
    • Uses:
      • Storing user data.
      • Managing inventory.
      • Handling financial transactions.

    Steps to Set Up a MySQL Database

    Step 1: Install MySQL

    • MySQL is often bundled with tools like XAMPP, WAMP, or MAMP.
    • If not installed, download and install MySQL from the MySQL website.

    Step 2: Access the MySQL Interface

    • Using phpMyAdmin:
      1. Open http://localhost/phpmyadmin.
      2. Login with:
        • Username: root
        • Password: Leave blank (default for XAMPP/WAMP).
    • Using MySQL Command-Line Interface (CLI):
      bash
      mysql -u root -p

    Step 3: Create a Database

    • Using phpMyAdmin:
      1. Go to the Databases tab.
      2. Enter a name for the database (e.g., test_db).
      3. Click Create.
    • Using MySQL CLI:
      sql
      CREATE DATABASE test_db;
    • Verify Database:
      sql
      SHOW DATABASES;

    Step 4: Create a Table

    • Using phpMyAdmin:
      1. Select your database.
      2. Go to the SQL tab and run the following query:
        sql
        CREATE TABLE users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(50) NOT NULL,
        email VARCHAR(100) NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        );
    • Using MySQL CLI:
      sql

      USE test_db;

      CREATE TABLE users (
      id INT AUTO_INCREMENT PRIMARY KEY,
      name VARCHAR(50) NOT NULL,
      email VARCHAR(100) NOT NULL,
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      );


    Insert Sample Data

    • SQL Query:
      sql
      INSERT INTO users (name, email) VALUES
      ('Alice', 'alice@example.com'),
      ('Bob', 'bob@example.com');

    13.2 Connecting PHP with MySQL

    Methods of Database Connection

    1. MySQLi:
      • Procedural and object-oriented interface.
      • Supports MySQL only.
    2. PDO (PHP Data Objects):
      • Object-oriented interface.
      • Supports multiple databases (MySQL, PostgreSQL, SQLite, etc.).

    Connecting Using MySQLi

    Procedural MySQLi

    php
    <?php
    // Connection parameters
    $host = "localhost";
    $username = "root";
    $password = "";
    $database = "test_db";
    // Connect to MySQL
    $conn = mysqli_connect($host, $username, $password, $database);

    // Check connection
    if (!$conn) {
    die(“Connection failed: “ . mysqli_connect_error());
    }
    echo “Connected successfully.”;
    ?>

    Object-Oriented MySQLi

    php
    <?php
    $host = "localhost";
    $username = "root";
    $password = "";
    $database = "test_db";
    // Create connection
    $conn = new mysqli($host, $username, $password, $database);

    // Check connection
    if ($conn->connect_error) {
    die(“Connection failed: “ . $conn->connect_error);
    }
    echo “Connected successfully.”;
    ?>


    Connecting Using PDO

    Basic Connection

    php
    <?php
    $host = "localhost";
    $username = "root";
    $password = "";
    $database = "test_db";
    try {
    $conn = new PDO(“mysql:host=$host;dbname=$database, $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo “Connected successfully.”;
    } catch (PDOException $e) {
    echo “Connection failed: “ . $e->getMessage();
    }
    ?>


    Querying the Database

    Using MySQLi

    Procedural:

    php
    <?php
    $result = mysqli_query($conn, "SELECT * FROM users");
    if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
    echo “Name: “ . $row[“name”] . “, Email: “ . $row[“email”] . “<br>”;
    }
    } else {
    echo “No results found.”;
    }
    ?>

    Object-Oriented:

    php
    <?php
    $result = $conn->query("SELECT * FROM users");
    if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
    echo “Name: “ . $row[“name”] . “, Email: “ . $row[“email”] . “<br>”;
    }
    } else {
    echo “No results found.”;
    }
    ?>

    Using PDO

    php
    <?php
    $stmt = $conn->query("SELECT * FROM users");
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo "Name: " . $row["name"] . ", Email: " . $row["email"] . "<br>";
    }
    ?>

    Error Handling in Connections

    MySQLi Procedural

    php
    if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
    }

    PDO with Exception

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

    Practical Example: User Management

    Insert Data

    Using PDO

    php
    <?php
    $name = "Charlie";
    $email = "charlie@example.com";
    $stmt = $conn->prepare(“INSERT INTO users (name, email) VALUES (:name, :email)”);
    $stmt->bindParam(‘:name’, $name);
    $stmt->bindParam(‘:email’, $email);
    $stmt->execute();

    echo “New record created successfully.”;
    ?>


    Delete Data

    php
    <?php
    $id = 1;
    $stmt = $conn->prepare(“DELETE FROM users WHERE id = :id”);
    $stmt->bindParam(‘:id’, $id);
    $stmt->execute();

    echo “Record deleted successfully.”;
    ?>


    Activities and Exercises

    1. Database Setup:
      • Create a database library with a table books (columns: id, title, author, published_year).
    2. Basic Connection:
      • Write a script to connect to the library database using both MySQLi and PDO.
    3. CRUD Operations:
      • Implement Create, Read, Update, and Delete operations for the books table using PDO.

    Assignment

    1. Create a tasks table with the following structure:
      • id (INT, Auto Increment, Primary Key)
      • task_name (VARCHAR, 100)
      • status (ENUM: pending, completed)
    2. Implement the following using PHP and MySQL:
      • Insert a new task into the tasks table.
      • Display all tasks in a table format.
      • Update the status of a task.
      • Delete a task.

    Summary

    In this lesson, you learned:

    1. How to set up a MySQL database and create tables.
    2. How to connect PHP with MySQL using MySQLi and PDO.
    3. How to perform basic CRUD operations.

    These skills form the foundation for creating dynamic web applications. Let me know if you’d like more examples or exercises!

  • Lesson 11: Advanced OOP Concepts

    In this lesson, you will learn advanced Object-Oriented Programming (OOP) concepts in PHP, including inheritance, polymorphism, abstract classes, and interfaces. These concepts are critical for building reusable, scalable, and modular PHP applications.


    11.1 Inheritance

    What is Inheritance?

    • Inheritance allows a class (child class) to inherit properties and methods from another class (parent class).
    • Promotes code reuse and helps in extending the functionality of existing classes.

    Syntax

    php
    class ParentClass {
    // Properties and methods
    }
    class ChildClass extends ParentClass {
    // Additional properties and methods
    }

    Example: Inheritance

    php
    <?php
    // Parent class
    class Animal {
    public $name;
    public function eat() {
    echo $this->name is eating.<br>”;
    }
    }

    // Child class
    class Dog extends Animal {
    public function bark() {
    echo $this->name is barking.<br>”;
    }
    }

    // Creating an object of the child class
    $dog = new Dog();
    $dog->name = “Buddy”;
    $dog->eat(); // Outputs: Buddy is eating.
    $dog->bark(); // Outputs: Buddy is barking.
    ?>


    Overriding Methods

    • A child class can override a method from the parent class to provide a new implementation.
    php
    <?php
    class Animal {
    public function makeSound() {
    echo "Animal makes a sound.<br>";
    }
    }
    class Cat extends Animal {
    public function makeSound() {
    echo “Cat meows.<br>”;
    }
    }

    $cat = new Cat();
    $cat->makeSound(); // Outputs: Cat meows.
    ?>


    Using parent::

    • Use parent:: to call the parent class’s method inside the child class.
    php
    <?php
    class Animal {
    public function makeSound() {
    echo "Animal makes a sound.<br>";
    }
    }
    class Dog extends Animal {
    public function makeSound() {
    parent::makeSound(); // Call parent class method
    echo “Dog barks.<br>”;
    }
    }

    $dog = new Dog();
    $dog->makeSound();
    // Outputs:
    // Animal makes a sound.
    // Dog barks.
    ?>


    11.2 Polymorphism

    What is Polymorphism?

    • Polymorphism means “many forms.” It allows objects of different classes to be treated as objects of a common parent class.
    • Achieved through method overriding and interfaces.

    Example: Polymorphism

    php
    <?php
    class Animal {
    public function makeSound() {
    echo "Animal makes a sound.<br>";
    }
    }
    class Dog extends Animal {
    public function makeSound() {
    echo “Dog barks.<br>”;
    }
    }

    class Cat extends Animal {
    public function makeSound() {
    echo “Cat meows.<br>”;
    }
    }

    function makeAnimalSound(Animal $animal) {
    $animal->makeSound();
    }

    $dog = new Dog();
    $cat = new Cat();

    makeAnimalSound($dog); // Outputs: Dog barks.
    makeAnimalSound($cat); // Outputs: Cat meows.
    ?>


    11.3 Abstract Classes

    What is an Abstract Class?

    • An abstract class serves as a blueprint for other classes.
    • It cannot be instantiated directly.
    • It can have both abstract (unimplemented) and non-abstract (implemented) methods.

    Syntax

    php
    abstract class AbstractClass {
    abstract protected function abstractMethod();
    public function concreteMethod() {
    // Implemented method
    }
    }

    Example: Abstract Class

    php
    <?php
    abstract class Animal {
    abstract public function makeSound(); // Abstract method
    public function eat() {
    echo “This animal is eating.<br>”; // Non-abstract method
    }
    }

    class Dog extends Animal {
    public function makeSound() {
    echo “Dog barks.<br>”;
    }
    }

    class Cat extends Animal {
    public function makeSound() {
    echo “Cat meows.<br>”;
    }
    }

    $dog = new Dog();
    $dog->makeSound(); // Outputs: Dog barks.
    $dog->eat(); // Outputs: This animal is eating.

    $cat = new Cat();
    $cat->makeSound(); // Outputs: Cat meows.
    ?>


    11.4 Interfaces

    What is an Interface?

    • An interface defines a contract that implementing classes must follow.
    • All methods in an interface are abstract by default.
    • A class can implement multiple interfaces, allowing for multiple inheritances.

    Syntax

    php
    interface InterfaceName {
    public function methodName();
    }
    class ClassName implements InterfaceName {
    public function methodName() {
    // Implementation
    }
    }


    Example: Interface

    php
    <?php
    interface Animal {
    public function makeSound();
    }
    class Dog implements Animal {
    public function makeSound() {
    echo “Dog barks.<br>”;
    }
    }

    class Cat implements Animal {
    public function makeSound() {
    echo “Cat meows.<br>”;
    }
    }

    $dog = new Dog();
    $dog->makeSound(); // Outputs: Dog barks.

    $cat = new Cat();
    $cat->makeSound(); // Outputs: Cat meows.
    ?>


    Extending Multiple Interfaces

    php
    <?php
    interface Animal {
    public function eat();
    }
    interface Pet {
    public function play();
    }

    class Dog implements Animal, Pet {
    public function eat() {
    echo “Dog is eating.<br>”;
    }

    public function play() {
    echo “Dog is playing.<br>”;
    }
    }

    $dog = new Dog();
    $dog->eat(); // Outputs: Dog is eating.
    $dog->play(); // Outputs: Dog is playing.
    ?>


    Practical Example: Combining Concepts

    Example: Shape Class

    php
    <?php
    abstract class Shape {
    abstract public function calculateArea();
    }
    class Rectangle extends Shape {
    private $width;
    private $height;

    public function __construct($width, $height) {
    $this->width = $width;
    $this->height = $height;
    }

    public function calculateArea() {
    return $this->width * $this->height;
    }
    }

    class Circle extends Shape {
    private $radius;

    public function __construct($radius) {
    $this->radius = $radius;
    }

    public function calculateArea() {
    return pi() * $this->radius * $this->radius;
    }
    }

    $shapes = [
    new Rectangle(5, 10),
    new Circle(7)
    ];

    foreach ($shapes as $shape) {
    echo “Area: “ . $shape->calculateArea() . “<br>”;
    }
    ?>


    Activities and Exercises

    1. Inheritance:
      • Create a Vehicle class and a Car class that extends it. Add methods for starting and stopping the vehicle.
    2. Polymorphism:
      • Implement a function that takes a Shape object (Rectangle, Circle, etc.) and prints its area.
    3. Abstract Classes:
      • Create an abstract class Payment with an abstract method processPayment(). Implement it in classes for CreditCardPayment and PaypalPayment.
    4. Interfaces:
      • Create an interface Logger with a method logMessage(). Implement the interface in classes for FileLogger and DatabaseLogger.

    Assignment

    1. Create an abstract class Employee with:
      • Properties: name, salary.
      • Abstract method calculateBonus().
    2. Implement two child classes:
      • Manager with a bonus of 20% of the salary.
      • Developer with a bonus of 10% of the salary.
    3. Create a script to calculate and display the bonus for both managers and developers.

    Summary

    In this lesson, you learned:

    1. How to use inheritance to extend functionality.
    2. How polymorphism allows different objects to be treated uniformly.
    3. How abstract classes and interfaces define reusable blueprints for classes.

    These advanced concepts form the backbone of scalable and maintainable PHP applications. Let me know if you need more examples or exercises!

  • Lesson 10: Introduction to OOP

    Object-Oriented Programming (OOP) is a programming paradigm that organizes code into objects and classes. This lesson provides an introduction to OOP in PHP, focusing on classes, objects, constructors, and destructors.


    10.1 Classes and Objects

    What is a Class?

    • A class is a blueprint for creating objects. It defines the properties (attributes) and methods (functions) that an object can have.
    • Syntax:
      php
      class ClassName {
      // Properties
      public $property1;
      public $property2;
      // Methods
      public function method1() {
      // Code for the method
      }
      }

    What is an Object?

    • An object is an instance of a class. It contains the data and methods defined by the class.
    • Creating an Object:
      php
      $object = new ClassName();

    Example: Basic Class and Object

    php
    <?php
    // Define a class
    class Car {
    public $make;
    public $model;
    public function displayDetails() {
    echo “Car Make: “ . $this->make . “, Model: “ . $this->model . “<br>”;
    }
    }// Create an object of the class
    $car1 = new Car();
    $car1->make = “Toyota”;
    $car1->model = “Corolla”;
    $car1->displayDetails(); // Outputs: Car Make: Toyota, Model: Corolla

    $car2 = new Car();
    $car2->make = “Honda”;
    $car2->model = “Civic”;
    $car2->displayDetails(); // Outputs: Car Make: Honda, Model: Civic
    ?>

    • Key Concepts:
      • $this: Refers to the current object.
      • Properties: Variables inside a class.
      • Methods: Functions inside a class.

    10.2 Access Modifiers

    What are Access Modifiers?

    Access modifiers define the visibility of class properties and methods.

    Modifier Description
    public Accessible from anywhere (default).
    protected Accessible only within the class and subclasses.
    private Accessible only within the class where it is defined.

    Example: Access Modifiers

    php
    <?php
    class Person {
    public $name; // Accessible from anywhere
    protected $age; // Accessible within the class and subclasses
    private $salary; // Accessible only within the class
    public function setDetails($name, $age, $salary) {
    $this->name = $name;
    $this->age = $age;
    $this->salary = $salary;
    }public function displayDetails() {
    echo “Name: $this->name, Age: $this->age<br>”;
    }
    }

    $person = new Person();
    $person->setDetails(“Alice”, 30, 50000);
    $person->displayDetails(); // Outputs: Name: Alice, Age: 30
    // echo $person->salary; // Error: Cannot access private property
    ?>


    10.3 Constructors

    What is a Constructor?

    • A constructor is a special method that automatically runs when an object is created.
    • Used to initialize properties or perform setup tasks.

    Syntax

    php
    public function __construct(parameters) {
    // Initialization code
    }

    Example: Using a Constructor

    php
    <?php
    class Book {
    public $title;
    public $author;
    // Constructor
    public function __construct($title, $author) {
    $this->title = $title;
    $this->author = $author;
    }public function displayDetails() {
    echo “Title: $this->title, Author: $this->author<br>”;
    }
    }

    // Create an object with constructor parameters
    $book1 = new Book(“1984”, “George Orwell”);
    $book1->displayDetails(); // Outputs: Title: 1984, Author: George Orwell

    $book2 = new Book(“To Kill a Mockingbird”, “Harper Lee”);
    $book2->displayDetails(); // Outputs: Title: To Kill a Mockingbird, Author: Harper Lee
    ?>


    10.4 Destructors

    What is a Destructor?

    • A destructor is a special method that is automatically called when an object is destroyed or goes out of scope.
    • Useful for cleanup tasks like closing database connections or releasing resources.

    Syntax

    php
    public function __destruct() {
    // Cleanup code
    }

    Example: Using a Destructor

    php
    <?php
    class FileHandler {
    private $filename;
    // Constructor
    public function __construct($filename) {
    $this->filename = $filename;
    echo “Opening file: $filename<br>”;
    }// Destructor
    public function __destruct() {
    echo “Closing file: $this->filename<br>”;
    }
    }

    // Create an object
    $file = new FileHandler(“data.txt”);
    // Destructor is automatically called when the script ends or object is no longer in use
    ?>

    Output:

    kotlin
    Opening file: data.txt
    Closing file: data.txt

    Practical Example: Combining Concepts

    Example: E-Commerce Product Class

    php
    <?php
    class Product {
    public $name;
    private $price;
    // Constructor
    public function __construct($name, $price) {
    $this->name = $name;
    $this->price = $price;
    }public function displayProduct() {
    echo “Product: $this->name, Price: $this->price<br>”;
    }

    // Destructor
    public function __destruct() {
    echo “Removing product: $this->name<br>”;
    }
    }

    $product1 = new Product(“Laptop”, 1500);
    $product1->displayProduct();

    $product2 = new Product(“Smartphone”, 800);
    $product2->displayProduct();
    ?>


    Activities and Exercises

    1. Classes and Objects:
      • Create a Car class with properties for make, model, and year. Add a method to display these details.
    2. Access Modifiers:
      • Modify the Car class to use protected for model and private for year. Add methods to get and set these properties.
    3. Constructors:
      • Create a Student class with properties for name and grade. Use a constructor to initialize these properties and display them using a method.
    4. Destructors:
      • Create a DatabaseConnection class that opens a connection in the constructor and closes it in the destructor.

    Assignment

    1. Create a BankAccount class with:
      • Properties: accountNumber (public), balance (private).
      • Methods:
        • A constructor to initialize the account number and starting balance.
        • A method deposit($amount) to add funds.
        • A method withdraw($amount) to subtract funds if sufficient balance exists.
        • A method displayBalance() to show the current balance.
      • Implement access modifiers for security.
      • Use a destructor to print a message when the account object is destroyed.
    2. Test the class with multiple account objects and perform deposit/withdraw operations.

    Summary

    In this lesson, you learned:

    1. The basics of classes and objects in PHP.
    2. How to use access modifiers to control visibility.
    3. How constructors and destructors work to manage initialization and cleanup tasks.

    These concepts are fundamental to creating reusable and scalable PHP applications. Let me know if you’d like more exercises or examples!

  • Lesson 9: PHP Sessions and Cookies

    In this lesson, we will explore how to manage state in PHP using cookies and sessions. These tools allow you to store data about users and their interactions with your website, providing the foundation for features like user authentication, shopping carts, and preferences.


    9.1 Setting and Retrieving Cookies

    What are Cookies?

    • Definition: Small pieces of data stored on the client’s browser.
    • Purpose: Track user activity, preferences, or login sessions.
    • Lifetime: Cookies can persist for a set duration or until the browser is closed.

    Setting Cookies

    Use the setcookie() function to create cookies.

    • Syntax:
      php
      setcookie(name, value, expire, path, domain, secure, httponly);
      • name: Name of the cookie.
      • value: Value to be stored.
      • expire: Expiration time in UNIX timestamp format.
      • path: Path where the cookie is accessible.
      • domain: Domain where the cookie is valid.
      • secure: Whether to transmit over HTTPS only.
      • httponly: Restrict cookie access to HTTP(S) protocols only.

    Example: Setting a Cookie

    php
    <?php
    // Set a cookie that expires in 1 hour
    setcookie("username", "JohnDoe", time() + 3600);
    echo "Cookie has been set.";
    ?>

    Retrieving Cookies

    Access cookies using the $_COOKIE superglobal.

    php
    <?php
    if (isset($_COOKIE["username"])) {
    echo "Welcome back, " . $_COOKIE["username"];
    } else {
    echo "Hello, guest!";
    }
    ?>

    Example: Deleting a Cookie

    • Set the expiration time to a past date.
    php
    <?php
    setcookie("username", "", time() - 3600);
    echo "Cookie has been deleted.";
    ?>

    9.2 Working with Sessions

    What are Sessions?

    • Definition: Sessions store data on the server for a user during their visit.
    • Purpose: Keep track of user data across multiple pages (e.g., shopping cart, login state).
    • Lifetime: Active until the user closes the browser or the session times out.

    Starting a Session

    • Use the session_start() function at the beginning of your script to initialize a session.
    • Syntax:
      php
      session_start();

    Storing Session Data

    • Store data in the $_SESSION superglobal array.
    php
    <?php
    session_start();
    $_SESSION["username"] = "JohnDoe";
    echo "Session has been set.";
    ?>

    Accessing Session Data

    • Access session variables using the $_SESSION array.
    php
    <?php
    session_start();
    if (isset($_SESSION["username"])) {
    echo "Welcome, " . $_SESSION["username"];
    } else {
    echo "Session not set.";
    }
    ?>

    Destroying a Session

    • Use session_unset() to clear session variables and session_destroy() to terminate the session.
    php
    <?php
    session_start();
    session_unset(); // Clears all session variables
    session_destroy(); // Destroys the session
    echo "Session has been destroyed.";
    ?>

    Comparison of Cookies and Sessions

    Feature Cookies Sessions
    Storage Client-side Server-side
    Security Less secure (stored in the browser) More secure (stored on the server)
    Data Size Limited (4KB per cookie) Unlimited (depends on server memory)
    Lifetime Can persist after browser is closed Ends when browser is closed or timed out
    Use Cases Remember user preferences or login state Shopping carts, user authentication

    Practical Examples

    Example 1: Login System with Sessions

    1. Login Form:
      php
      <form method="POST" action="login.php">
      Username: <input type="text" name="username"><br>
      <input type="submit" value="Login">
      </form>
    2. Processing Login:
      php
      <?php
      session_start();
      if ($_SERVER["REQUEST_METHOD"] == "POST") {
      $_SESSION["username"] = $_POST["username"];
      echo "Welcome, " . $_SESSION["username"];
      }
      ?>
    3. Displaying User Data:
      php
      <?php
      session_start();
      if (isset($_SESSION["username"])) {
      echo "Hello, " . $_SESSION["username"];
      } else {
      echo "Please log in.";
      }
      ?>
    4. Logout:
      php
      <?php
      session_start();
      session_unset();
      session_destroy();
      echo "You have logged out.";
      ?>

    Example 2: Remember Me with Cookies

    1. Login Form:
      php
      <form method="POST" action="remember_me.php">
      Username: <input type="text" name="username"><br>
      <input type="checkbox" name="remember" value="1"> Remember Me<br>
      <input type="submit" value="Login">
      </form>
    2. Processing Login:
      php
      <?php
      if ($_SERVER["REQUEST_METHOD"] == "POST") {
      $username = $_POST["username"];
      if (isset($_POST["remember"])) {
      setcookie("username", $username, time() + 3600); // Cookie valid for 1 hour
      }
      echo "Welcome, $username";
      }
      ?>
    3. Displaying User Data:
      php
      <?php
      if (isset($_COOKIE["username"])) {
      echo "Welcome back, " . $_COOKIE["username"];
      } else {
      echo "Please log in.";
      }
      ?>

    Activities and Exercises

    1. Cookies:
      • Create a script to set a cookie for the user’s preferred language. Display a greeting in that language on subsequent visits.
    2. Sessions:
      • Build a shopping cart system using sessions where users can add, view, and clear items.
    3. Combination:
      • Create a login system that uses sessions for authentication and cookies for remembering the username.

    Assignment

    1. Part 1: Using Cookies
      • Create a form where users can input their favorite color.
      • Save the color in a cookie and display the page’s background in that color when revisited.
    2. Part 2: Using Sessions
      • Create a multi-page application:
        1. A form on Page 1 collects the user’s name.
        2. Page 2 displays a personalized greeting using session data.
        3. A logout button on Page 3 clears the session.

    Summary

    In this lesson, you learned how to:

    1. Set, retrieve, and delete cookies in PHP.
    2. Work with sessions to manage user data across multiple pages.
    3. Understand the differences and use cases for cookies and sessions.

    These skills are essential for creating dynamic, user-focused web applications. Let me know if you’d like additional examples or exercises!

    You said:
  • Lesson 8: Handling Forms in PHP

    Forms are a vital part of web applications, enabling user interaction and data submission. This lesson covers handling form submissions using PHP, differentiating between GET and POST methods, and securing user input through validation and sanitization.


    8.1 GET vs POST

    What are GET and POST Methods?

    Both GET and POST are HTTP request methods used to send data from a client (browser) to a server.

    GET Method

    • Data is sent in the URL.
    • Advantages:
      • Can be bookmarked or shared.
      • Useful for non-sensitive data like search queries.
    • Disadvantages:
      • Limited amount of data (URL length restrictions).
      • Data is visible in the URL, not suitable for sensitive data.
    • Example:
    • <form method=”GET” action=”process.php”>


      >/form>

      URL after submission: process.php?username=value


    POST Method

    • Data is sent in the HTTP request body.
    • Advantages:
      • Secure for sensitive data (passwords, personal information).
      • No limit on data size.
    • Disadvantages:
      • Cannot be bookmarked or shared.
    • Example:
    • <?php



      ?>


    Handling GET and POST Data in PHP

    • Using $_GET:
    • <?php
      if (isset($_GET[‘username’])) {
      echo “Username: ” . htmlspecialchars($_GET[‘username’]);
      }
      ?>
    • Using $_POST:
    • <?php
      if (isset($_POST[‘username’])) {
      echo “Username: ” . htmlspecialchars($_POST[‘username’]);
      }
      ?>

    8.2 Form Validation

    Why Validate Forms?

    • Ensures data integrity and security.
    • Prevents malicious input, such as SQL injection or XSS attacks.
    • Enhances user experience with immediate feedback.

    Common Validation Rules

    1. Required Fields: Ensure that critical fields are not left empty.
    2. Data Type Validation: Check if the input matches the expected format (e.g., email, number).
    3. Length Validation: Limit the number of characters.
    4. Custom Rules: Define application-specific rules (e.g., password complexity).

    Example: Validating Required Fields

    <?php
    if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
    $name = trim($_POST[‘name’]);
    $email = trim($_POST[’email’]);

    if (empty($name)) {
    echo “Name is required.
    “;
    }

    if (empty($email)) {
    echo “Email is required.
    “;
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo “Invalid email format.
    “;
    }
    }
    ?>

    Name:
    Email:


    8.3 Sanitizing and Validating Input

    Sanitization vs Validation

    • Sanitization: Cleans input by removing unwanted characters (e.g., HTML tags, special characters).
    • Validation: Ensures input meets specific criteria (e.g., correct email format).

    Sanitizing Input

    PHP provides the filter_var() function for sanitization.

    <?php
    $dirty_email = “user@example.com”;
    $clean_email = filter_var($dirty_email, FILTER_SANITIZE_EMAIL);
    echo $clean_email; // Outputs: user@example.com
    ?>

    Validating Input

    PHP provides several filters for validation.

    <?php
    $email = “user@example.com”;

    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo “Valid email.”;
    } else {
    echo “Invalid email.”;
    }
    ?>


    Combining Sanitization and Validation

    <?php
    if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
    $email = filter_var(trim($_POST[’email’]), FILTER_SANITIZE_EMAIL);

    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo “Valid email: $email”;
    } else {
    echo “Invalid email format.”;
    }
    }
    ?>

    Email:


    Validating Multiple Inputs

    <?php
    if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
    $name = htmlspecialchars(trim($_POST[‘name’]));
    $email = filter_var(trim($_POST[’email’]), FILTER_SANITIZE_EMAIL);
    $age = filter_var(trim($_POST[‘age’]), FILTER_SANITIZE_NUMBER_INT);

    if (empty($name)) {
    echo “Name is required.
    “;
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo “Invalid email format.
    “;
    }

    if ($age < 1 || $age > 120) {
    echo “Invalid age.
    “;
    }
    }
    ?>

    Name:
    Email:
    Age:


    Activities and Exercises

    1. GET vs POST:
      • Create a form with GET and POST methods to submit a username. Display the username after submission.
    2. Form Validation:
      • Build a form with fields for name, email, and age. Validate all fields to ensure they are filled correctly.
    3. Sanitization and Validation:
      • Write a script that accepts a URL input, sanitizes it, and validates if it is a valid URL.

    Assignment

    1. Create a PHP script with a form to collect:
      • Full Name
      • Email Address
      • Age
      • Phone Number
    2. Implement:
      • Validation rules:
        • Name and email are required.
        • Email must be in a valid format.
        • Age must be a number between 1 and 120.
        • Phone number must contain only digits and be 10–15 characters long.
      • Sanitization for all inputs.
    3. Display:
      • Error messages for invalid inputs.
      • A success message and the sanitized data if all inputs are valid.

    Summary

    In this lesson, you learned how to:

    1. Differentiate between GET and POST methods.
    2. Handle and validate form data in PHP.
    3. Sanitize user inputs to secure your application.

    These skills are critical for building secure and user-friendly web applications. Let me know if you’d like further clarification or examples!

  • Lesson 7: Arrays in PHP

    Arrays are one of the most important data structures in PHP. They allow you to store and manage multiple values in a single variable. This lesson will cover the three types of arrays in PHP: Indexed, Associative, and Multidimensional arrays. Additionally, we will explore commonly used array functions.


    7.1 Indexed Arrays

    What is an Indexed Array?

    • An indexed array stores a series of elements, each assigned an index starting from 0.
    • Elements in an indexed array are accessed using numeric indices.

    Creating an Indexed Array

    • Using the array() function:
    • <?php
      $fruits = array(“Apple”, “Banana”, “Cherry”);
      ?>
    • Using shorthand syntax:
    • <?php
      $fruits = [“Apple”, “Banana”, “Cherry”];
      ?>

    Accessing Elements

    <?php
    $fruits = [“Apple”, “Banana”, “Cherry”];
    echo $fruits[0]; // Outputs: Apple
    echo $fruits[1]; // Outputs: Banana
    ?>

    Adding Elements

    <?php
    $fruits[] = “Orange”; // Adds “Orange” to the array
    ?>

    Looping Through an Indexed Array

    <?php
    $fruits = [“Apple”, “Banana”, “Cherry”];

    foreach ($fruits as $fruit) {
    echo $fruit . “
    “;
    }
    ?>


    7.2 Associative Arrays

    What is an Associative Array?

    • Associative arrays use named keys to access values instead of numeric indices.

    Creating an Associative Array

    <?php
    $person = array(
    “name” => “Alice”,
    “age” => 25,
    “city” => “New York”
    );
    ?>

    Accessing Elements

    <?php
    echo $person[“name”]; // Outputs: Alice
    echo $person[“age”]; // Outputs: 25
    ?>

    Adding Elements

    <?php
    $person[“country”] = “USA”; // Adds a new key-value pair
    ?>

    Looping Through an Associative Array

    <?php
    $person = array(
    “name” => “Alice”,
    “age” => 25,
    “city” => “New York”
    );

    foreach ($person as $key => $value) {
    echo “$key: $value
    “;
    }
    ?>


    7.3 Multidimensional Arrays

    What is a Multidimensional Array?

    • Multidimensional arrays are arrays that contain other arrays as elements.

    Creating a Multidimensional Array

    <?php
    $students = array(
    array(“Alice”, 25, “New York”),
    array(“Bob”, 22, “Los Angeles”),
    array(“Charlie”, 30, “Chicago”)
    );
    ?>

    Accessing Elements

    <?php
    echo $students[0][0]; // Outputs: Alice
    echo $students[1][2]; // Outputs: Los Angeles
    ?>

    Associative Multidimensional Array

    <?php
    $students = array(
    “Alice” => array(“age” => 25, “city” => “New York”),
    “Bob” => array(“age” => 22, “city” => “Los Angeles”)
    );

    echo $students[“Alice”][“city”]; // Outputs: New York
    ?>

    Looping Through a Multidimensional Array

    <?php
    $students = array(
    array(“Alice”, 25, “New York”),
    array(“Bob”, 22, “Los Angeles”),
    array(“Charlie”, 30, “Chicago”)
    );

    foreach ($students as $student) {
    echo “Name: $student[0], Age: $student[1], City: $student[2]
    “;
    }
    ?>


    7.4 Array Functions

    Commonly Used Array Functions

    1. count()

    • Returns the number of elements in an array.
    • Example:
    • <?php
      $fruits = [“Apple”, “Banana”, “Cherry”];
      echo count($fruits); // Outputs: 3
      ?>

    2. array_merge()

    • Merges two or more arrays into one.
    • Example:
    • <?php
      $array1 = [“a”, “b”];
      $array2 = [“c”, “d”];
      $merged = array_merge($array1, $array2);
      print_r($merged); // Outputs: Array ( [0] => a [1] => b [2] => c [3] => d )
      ?>

    3. array_push()

    • Adds one or more elements to the end of an array.
    • Example:
    • <?php
      $fruits = [“Apple”, “Banana”];
      array_push($fruits, “Cherry”, “Orange”);
      print_r($fruits); // Outputs: Array ( [0] => Apple [1] => Banana [2] => Cherry [3] => Orange )
      ?>

    4. array_pop()

    • Removes and returns the last element of an array.
    • Example:
    • <?php
      $fruits = [“Apple”, “Banana”, “Cherry”];
      $lastFruit = array_pop($fruits);
      echo $lastFruit; // Outputs: Cherry
      ?>

    5. in_array()

    • Checks if a value exists in an array.
    • Example:
    • <?php
      $fruits = [“Apple”, “Banana”, “Cherry”];
      echo in_array(“Banana”, $fruits) ? “Found” : “Not Found”; // Outputs: Found
      ?>

    6. array_keys()

    • Returns all the keys of an array.
    • Example:
    • <?php
      $person = [“name” => “Alice”, “age” => 25];
      $keys = array_keys($person);
      print_r($keys); // Outputs: Array ( [0] => name [1] => age )
      ?>

    7. array_values()

    • Returns all the values of an array.
    • Example:
    • <?php
      $person = [“name” => “Alice”, “age” => 25];
      $values = array_values($person);
      print_r($values); // Outputs: Array ( [0] => Alice [1] => 25 )
      ?>

    8. sort() and rsort()

    • sort(): Sorts an array in ascending order.
    • rsort(): Sorts an array in descending order.
    • Example:
    • <?php
      $numbers = [3, 1, 4, 1, 5];
      sort($numbers);
      print_r($numbers); // Outputs: Array ( [0] => 1 [1] => 1 [2] => 3 [3] => 4 [4] => 5 )
      ?>

    9. array_reverse()

    • Reverses the order of array elements.
    • Example:
    • <?php
      $fruits = [“Apple”, “Banana”, “Cherry”];
      $reversed = array_reverse($fruits);
      print_r($reversed); // Outputs: Array ( [0] => Cherry [1] => Banana [2] => Apple )
      ?>

    10. array_search()

    • Searches for a value in an array and returns its key.
    • Example:
    • <?php
      $fruits = [“Apple”, “Banana”, “Cherry”];
      echo array_search(“Banana”, $fruits); // Outputs: 1
      ?>

    Activities and Exercises

    1. Indexed Array:
      • Create an array of your favorite movies and display each movie using a loop.
    2. Associative Array:
      • Create an associative array representing a book (title, author, price) and display its details.
    3. Multidimensional Array:
      • Create an array of students with their name, age, and city. Display all students using nested loops.
    4. Array Functions:
      • Write a script to sort an array of numbers in descending order.

    Assignment

    Create a PHP script that:

    1. Stores details of products (name, price, category) in a multidimensional array.
    2. Displays all products using a loop.
    3. Sorts the products by price in ascending order.
    4. Searches for a product by name and displays its details.

    Summary

    In this lesson, you learned:

    • The three types of arrays in PHP: Indexed, Associative, and Multidimensional.
    • How to use key PHP array functions for managing arrays effectively.

    Arrays are versatile and foundational in PHP, making them critical for handling complex data structures. Let me know if you need additional examples or exercises!

  • Lesson 6: Functions in PHP

    Functions in PHP are reusable blocks of code that perform specific tasks. They help make code modular, efficient, and easier to debug. This lesson will explore defining and calling functions, working with parameters and return values, and understanding variable scope and global variables.


    6.1 Defining and Calling Functions

    What is a Function?

    • A function is a block of code that executes when called.
    • Functions can accept inputs (parameters) and return outputs.

    Syntax

    <?php
    function functionName() {
    // Code to be executed
    }
    ?>

    Defining a Function

    <?php
    function sayHello() {
    echo “Hello, World!”;
    }
    ?>

    Calling a Function

    <?php
    sayHello(); // Outputs: Hello, World!
    ?>

    Example: Function with a Task

    <?php
    function displayDate() {
    echo “Today’s date is ” . date(“Y-m-d”) . “
    “;
    }

    displayDate(); // Outputs today’s date
    displayDate(); // Can be reused
    ?>


    6.2 Function Parameters and Return Values

    Parameters

    • Parameters are variables passed to a function when it is called.
    • Syntax:
    • <?php
      function functionName($param1, $param2) {
      // Code that uses $param1 and $param2
      }
      ?>

    Example: Function with Parameters

    <?php

    function greet($name) {
    echo “Hello, $name!
    “;
    }

    greet(“Alice”); // Outputs: Hello, Alice!
    greet(“Bob”); // Outputs: Hello, Bob!
    ?>

    Default Parameter Values

    • Parameters can have default values.
    • Example:
    • <?php
      function greet($name = “Guest”) {
      echo “Hello, $name!
      “;
      }

      greet(); // Outputs: Hello, Guest!
      greet(“Alice”); // Outputs: Hello, Alice!
      ?>


    Return Values

    • A function can return a value using the return keyword.
    • Syntax:
    • <?php
      function functionName($param) {
      return $value;
      }
      ?>

    Example: Function with Return Value

    <?php
    function add($a, $b) {
    return $a + $b;
    }

    $result = add(5, 10); // Returns 15
    echo “Sum: $result
    “;
    ?>

    Example: Function with Multiple Parameters and Return

    <?php
    function calculateArea($length, $width) {
    return $length * $width;
    }

    $area = calculateArea(5, 10); // Returns 50
    echo “Area: $area
    “;
    ?>


    Combining Parameters and Return Values

    <?php
    function calculateDiscount($price, $discountRate) {
    $discount = $price * ($discountRate / 100);
    return $price – $discount;
    }

    $finalPrice = calculateDiscount(100, 10); // Returns 90
    echo “Final Price: $finalPrice
    “;
    ?>


    6.3 Variable Scope and Global Variables

    What is Variable Scope?

    Scope determines where a variable can be accessed. PHP has:

    1. Local Scope
    2. Global Scope
    3. Static Variables

    Local Scope

    • Variables defined inside a function are local to that function.
    • Example:
    • <?php
      function testScope() {
      $localVar = “I’m local!”;
      echo $localVar; // Accessible here
      }

      testScope(); // Outputs: I’m local
      // echo $localVar; // Error: Undefined variable
      ?>


    Global Scope

    • Variables declared outside functions are global.
    • Example:
    • <?php
      $globalVar = “I’m global!”;

      function testGlobal() {
      // echo $globalVar; // Error: Undefined variable
      }

      testGlobal();
      ?>


    Accessing Global Variables Inside Functions

    • Use the global keyword or $GLOBALS array.
    • Example:
    • <?php
      $x = 5;
      $y = 10;

      function sumGlobal() {
      $sum = $GLOBALS[‘x’] + $GLOBALS[‘y’];
      echo “Sum: $sum
      “;
      }

      sumGlobal(); // Outputs: Sum: 15
      ?>


    Static Variables

    • Static variables retain their value between function calls.
    • Example:
    • <?php
      function counter() {
      static $count = 0;
      $count++;
      echo “Count: $count
      “;
      }

      counter(); // Outputs: Count: 1
      counter(); // Outputs: Count: 2
      counter(); // Outputs: Count: 3
      ?>


    Activities and Exercises

    1. Defining and Calling Functions:
      • Write a function that takes your name as input and outputs “Welcome, [Name]!”
    2. Function Parameters:
      • Create a function to calculate the perimeter of a rectangle. It should take length and width as inputs.
    3. Return Values:
      • Write a function that calculates the compound interest and returns the final amount.
    4. Global Variables:
      • Write a script where a global variable tracks the total sales of a shop across multiple function calls.
    5. Static Variables:
      • Create a function that counts how many times it has been called.

    Assignment

    Write a PHP script that:

    1. Defines a function calculateGrade to calculate a student’s grade based on their score.
      • Parameters: score
      • Return: Grade (A, B, C, or F based on the score)
      • Criteria:
        • 90 and above: A
        • 75–89: B
        • 50–74: C
        • Below 50: F
    2. Accepts a student’s score as input and displays their grade.

    Summary

    In this lesson, you learned how to:

    • Define and call functions.
    • Work with function parameters and return values.
    • Understand variable scope, global variables, and static variables.

    These concepts form the foundation for writing clean and modular PHP code. Let me know if you’d like additional examples or exercises!

  • Lesson 5: Control Structures

    Control structures in PHP enable developers to implement decision-making and repetitive tasks. This lesson covers conditional statements (if-else, switch-case) and loops (for, while, do-while, foreach) in detail, with examples and use cases.


    5.1 If-Else Statements

    What is an If-Else Statement?

    • If-else statements execute a block of code based on a condition.
    • Syntax:
    • <?php
      if (condition) {
      // Code to execute if condition is true
      } elseif (another_condition) {
      // Code to execute if another_condition is true
      } else {
      // Code to execute if no condition is true
      }
      ?>

    Example: Simple If-Else

    <?php
    = 18) {
    echo “You are eligible to vote.”;
    } else {
    echo “You are not eligible to vote.”;
    }
    ?>
    ?>

    Example: If-Elseif-Else

    <?php
    = 90) {
    echo “Grade: A”;
    } elseif ($score >= 75) {
    echo “Grade: B”;
    } else {
    echo “Grade: C”;
    }
    ?>
    ?>

    5.2 Switch-Case Statements

    What is a Switch-Case Statement?

    • A switch-case statement evaluates a variable against multiple possible values and executes corresponding code.
    • Syntax:
    • <?php
      switch (variable) {
      case value1:
      // Code to execute if variable equals value1
      break;
      case value2:
      // Code to execute if variable equals value2
      break;
      default:
      // Code to execute if no case matches
      }
      ?>

    Example: Switch-Case

    <?php

    ?>

    5.3 Loops

    Why Use Loops?

    Loops allow repetitive execution of code blocks as long as a specified condition is met.


    5.3.1 For Loop

    Syntax

    <?php
    for (initialization; condition; increment/decrement) {
    // Code to execute
    }
    ?>

    Example: Print Numbers

    <?php
    “;
    }
    ?>
    ?>

    Example: Multiplication Table

    <?php
    “;
    }
    ?>
    ?>

    5.3.2 While Loop

    Syntax

    <?php
    while (condition) {
    // Code to execute
    }
    ?>

    Example: Print Even Numbers

    <?php
    “;
    $num += 2;
    }
    ?>
    ?>

    Example: Factorial Calculation

    <?php
    0) {
    $factorial *= $n;
    $n–;
    }

    echo “Factorial: $factorial”;
    ?>
    ?>


    5.3.3 Do-While Loop

    Syntax

    <?php
    do {
    // Code to execute
    } while (condition);
    ?>

    Example: Print Numbers

    <?php
    “;
    $num++;
    } while ($num <= 5); ?>
    ?>

    Difference Between While and Do-While

    • In a while loop, the condition is checked before the first iteration.
    • In a do-while loop, the code executes at least once, even if the condition is false.

    5.3.4 Foreach Loop

    Purpose

    • Designed specifically for iterating over arrays.

    Syntax

    <?php
    foreach ($array as $value) {
    // Code to execute
    }
    ?>

    Example: Iterate Over Array

    <?php
    “;
    }
    ?>
    ?>

    Example: Key-Value Pairs

    <?php
    “Alice”, “Age” => 25, “City” => “New York”);

    foreach ($person as $key => $value) {
    echo “$key: $value
    “;
    }
    ?>
    ?>


    Activities and Exercises

    1. If-Else Statement:
      • Write a script to determine whether a given year is a leap year or not.
    2. Switch-Case Statement:
      • Create a script that takes a number (1–7) and outputs the corresponding day of the week.
    3. Loops:
      • Use a for loop to print the first 10 Fibonacci numbers.
      • Write a while loop that prints all odd numbers between 1 and 20.
      • Use a foreach loop to display all items in an associative array of student names and grades.

    Assignment

    Create a PHP script that:

    1. Uses an if-else statement to check whether a number is positive, negative, or zero.
    2. Uses a switch-case statement to output the month name when given a number (1–12).
    3. Uses a for loop to calculate the sum of numbers from 1 to 100.
    4. Uses a while loop to find the largest power of 2 less than a given number.
    5. Uses a foreach loop to display a list of products with their prices.

    Summary

    Control structures are crucial in PHP for decision-making and iteration. The concepts covered in this lesson form the backbone of logical programming in PHP and will be extensively used in real-world applications. Let me know if you’d like additional examples or exercises!