PHP Examples For Beginners: OOPS & PHP Example Part 2

Table of Contents

Task: 1

Implement a derived class “Triangle” that extends the “Shape” base class. Override the “calculateArea()” method in the “Triangle” class to calculate the area based on given dimensions. Create an object of the “Triangle” class and demonstrate the area calculation.

<!DOCTYPE html>
<html>
<head>
    <title>Triangle Area Calculation</title>
</head>
<body>
    <?php
    // Shape base class
    abstract class Shape {
        abstract public function calculateArea();
    }

    // Triangle derived class
    class Triangle extends Shape {
        private $base;
        private $height;

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

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

    // Process form submission
    if (isset($_POST['submit'])) {
        $base = $_POST['base'];
        $height = $_POST['height'];

        // Create an object of the Triangle class
        $triangle = new Triangle($base, $height);

        // Calculate the area of the triangle
        $area = $triangle->calculateArea();
    }
    ?>

    <h1>Triangle Area Calculation</h1>

    <form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
        <label for="base">Base:</label>
        <input type="number" name="base" required>

        <label for="height">Height:</label>
        <input type="number" name="height" required>

        <input type="submit" name="submit" value="Calculate">
    </form>

    <?php if (isset($_POST['submit'])): ?>
        <h2>Area: <?php echo $area; ?></h2>
    <?php endif; ?>
</body>
</html>

In this updated example, we have added an HTML form that allows users to input the base and height values of a triangle. When the form is submitted, PHP code is used to handle the form submission, create an object of the Triangle class, calculate the area, and display it on the page.

The form uses the POST method to send the form data to the same PHP file ($_SERVER['PHP_SELF']). The name attribute is used in the form of inputs to identify the input values in the PHP code.

In the PHP section, we check if the form has been submitted (isset($_POST['submit'])) to ensure the calculation is performed only when the form is submitted. If the form is submitted, we retrieve the base and height values from the $_POST array, create an object of the Triangle class with the provided values, calculate the area, and store it in the $area variable.

The calculated area is then displayed below the form by checking if the form has been submitted (isset($_POST['submit'])) using an if statement.

This updated example combines HTML and PHP to create an interactive form for calculating the area of a triangle based on user input.

Task: 2

Create a class called “Student” with properties such as name, age, and grade. Implement methods to add, update, and delete student records in a database using CRUD operations. Demonstrate the CRUD functionality for student records.

HTML Form (index.html):

<!DOCTYPE html>
<html>
<head>
    <title>Student Records</title>
</head>
<body>
    <h1>Student Records</h1>

    <form method="POST" action="process.php">
        <input type="hidden" name="action" value="add">

        <label for="name">Name:</label>
        <input type="text" name="name" required>

        <label for="age">Age:</label>
        <input type="number" name="age" required>

        <label for="grade">Grade:</label>
        <input type="text" name="grade" required>

        <input type="submit" name="submit" value="Add Student">
    </form>

    <h2>Edit Student</h2>
    <form method="POST" action="process.php">
        <input type="hidden" name="action" value="edit">

        <label for="edit-id">Student ID:</label>
        <input type="number" name="edit-id" required>

        <label for="edit-name">Name:</label>
        <input type="text" name="edit-name" required>

        <label for="edit-age">Age:</label>
        <input type="number" name="edit-age" required>

        <label for="edit-grade">Grade:</label>
        <input type="text" name="edit-grade" required>

        <input type="submit" name="submit" value="Edit Student">
    </form>

    <h2>Remove Student</h2>
    <form method="POST" action="process.php">
        <input type="hidden" name="action" value="remove">

        <label for="remove-id">Student ID:</label>
        <input type="number" name="remove-id" required>

        <input type="submit" name="submit" value="Remove Student">
    </form>
</body>
</html>

PHP Code (process.php):

<?php
// Student class
class Student {
    private $id;
    private $name;
    private $age;
    private $grade;
    private $db; // Database connection

    public function __construct() {
        // Initialize the database connection
        $this->db = new PDO("mysql:host=localhost;dbname=your_database_name", "your_username", "your_password");
    }

    public function addStudent($name, $age, $grade) {
        // Insert the student record into the database
        $stmt = $this->db->prepare("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)");
        $stmt->execute([$name, $age, $grade]);

        $this->id = $this->db->lastInsertId();
        $this->name = $name;
        $this->age = $age;
        $this->grade = $grade;
    }

    public function editStudent($id, $name, $age, $grade) {
        // Update the student record in the database
        $stmt = $this->db->prepare("UPDATE students SET name = ?, age = ?, grade = ? WHERE id = ?");
        $stmt->execute([$name, $age, $grade, $id]);

        $this->id = $id;
        $this->name = $name;
        $this->age = $age;
        $this->grade = $grade;
    }

    public function removeStudent($id) {
        // Delete the student record from thedatabase
        $stmt = $this->db->prepare("DELETE FROM students WHERE id = ?");
        $stmt->execute([$id]);

        $this->id = null;
        $this->name = null;
        $this->age = null;
        $this->grade = null;
    }
}

// Process form submission
if (isset($_POST['submit'])) {
    $action = $_POST['action'];
    $student = new Student();

    if ($action === 'add') {
        $name = $_POST['name'];
        $age = $_POST['age'];
        $grade = $_POST['grade'];

        $student->addStudent($name, $age, $grade);

        // Redirect to the success page
        header("Location: success.html");
        exit();
    } elseif ($action === 'edit') {
        $id = $_POST['edit-id'];
        $name = $_POST['edit-name'];
        $age = $_POST['edit-age'];
        $grade = $_POST['edit-grade'];

        $student->editStudent($id, $name, $age, $grade);

        // Redirect to the success page
        header("Location: success.html");
        exit();
    } elseif ($action === 'remove') {
        $id = $_POST['remove-id'];

        $student->removeStudent($id);

        // Redirect to the success page
        header("Location: success.html");
        exit();
    }
}
?>

HTML Success Page (success.html):

<!DOCTYPE html>
<html>
<head>
    <title>Success</title>
</head>
<body>
    <h1>Action Completed Successfully</h1>
    <p>The requested action has been completed successfully.</p>
</body>
</html>

Please ensure that you replace "your_database_name", "your_username", and "your_password" with your actual database details in the PDO connection.

In this updated example, the HTML form includes three sections: one for adding a student, one for editing a student, and one for removing a student. Each section has its own set of input fields and a hidden input field to identify the action to be performed.

The PHP code handles the form submission based on the action specified in the hidden input field. If the action is “add”, the addStudent method is called to add the student record to the database. If the action is “edit”, the editStudent method is called to update the student record. If the action is “remove”, the removeStudent method is called to delete the student record. After performing the respective action, the user is redirected to the success page (success.html).

The success page (success.html) displays a success message to indicate that the requested action has been completed successfully.

This updated example provides the complete functionality for adding, editing and removing student records using PHP and a simple HTML form.

Task: 3

Implement an abstract class called “Animal” with abstract methods such as “eat()” and “sound()”. Extend this class to create derived classes for specific animals like “Cat”, “Dog”, and “Bird”. Implement the abstract methods in the derived classes to provide specific behavior for each animal. Create objects of the derived classes and demonstrate the eating and sound behavior.

Here’s an example that includes the Add, Edit, and Remove functionality for the given task. It consists of HTML form, HTML code, and PHP code:

HTML Form (index.html):

<!DOCTYPE html>
<html>
<head>
    <title>Animal Records</title>
</head>
<body>
    <h1>Animal Records</h1>

    <form method="POST" action="process.php">
        <input type="hidden" name="action" value="add">

        <label for="name">Animal Name:</label>
        <input type="text" name="name" required>

        <label for="type">Animal Type:</label>
        <select name="type" required>
            <option value="Cat">Cat</option>
            <option value="Dog">Dog</option>
            <option value="Bird">Bird</option>
        </select>

        <input type="submit" name="submit" value="Add Animal">
    </form>

    <h2>Edit Animal</h2>
    <form method="POST" action="process.php">
        <input type="hidden" name="action" value="edit">

        <label for="edit-id">Animal ID:</label>
        <input type="number" name="edit-id" required>

        <label for="edit-name">Animal Name:</label>
        <input type="text" name="edit-name" required>

        <label for="edit-type">Animal Type:</label>
        <select name="edit-type" required>
            <option value="Cat">Cat</option>
            <option value="Dog">Dog</option>
            <option value="Bird">Bird</option>
        </select>

        <input type="submit" name="submit" value="Edit Animal">
    </form>

    <h2>Remove Animal</h2>
    <form method="POST" action="process.php">
        <input type="hidden" name="action" value="remove">

        <label for="remove-id">Animal ID:</label>
        <input type="number" name="remove-id" required>

        <input type="submit" name="submit" value="Remove Animal">
    </form>
</body>
</html>

PHP Code (process.php):

<?php
// Animal abstract class
abstract class Animal {
    protected $name;
    protected $type;

    abstract public function eat();
    abstract public function sound();
}

// Cat class
class Cat extends Animal {
    public function __construct($name) {
        $this->name = $name;
        $this->type = "Cat";
    }

    public function eat() {
        return "The cat is eating.";
    }

    public function sound() {
        return "Meow!";
    }
}

// Dog class
class Dog extends Animal {
    public function __construct($name) {
        $this->name = $name;
        $this->type = "Dog";
    }

    public function eat() {
        return "The dog is eating.";
    }

    public function sound() {
        return "Woof!";
    }
}

// Bird class
class Bird extends Animal {
    public function __construct($name) {
        $this->name = $name;
        $this->type = "Bird";
    }

    public function eat() {
        return "The bird is eating.";
    }

    public function sound() {
        return "Chirp!";
    }
}

// Process form submission
if (isset($_POST['submit'])) {
    $action = $_POST['action'];

    if ($action === 'add') {
        $name = $_POST['name'];
        $type = $_POST['type'];

        // Create a new animal object based on the selected type
        if ($type === 'Cat') {
            $animal = new Cat($name);
        } elseif ($type === 'Dog') {
            $animal = new Dog($name);
        } elseif ($type === 'Bird') {
            $animal = new Bird($name);
        }

        // Perform the eat and sound behavior
        $eatBehavior = $animal->eat();
        $soundBehavior = $animal->sound();

        // Display the behaviors
        echo "<h1>$name ($type)</h1>";
        echo "<p>$eatBehavior</p>";
        echo "<p>$soundBehavior</p>";
    } elseif ($action === 'edit') {
        $id = $_POST['edit-id'];
        $name = $_POST['edit-name'];
        $type = $_POST['edit-type'];

        // Update the animal record based on the selected type
        if ($type === 'Cat') {
            $animal = new Cat($name);
        } elseif ($type === 'Dog') {
            $animal = new Dog($name);
        } elseif ($type === 'Bird') {
            $animal = new Bird($name);
        }

        // Perform the eat and sound behavior
        $eatBehavior = $animal->eat();
        $soundBehavior = $animal->sound();

        // Display the updated behaviors
        echo "<h1>Updated Animal Record:</h1>";
        echo "<p>ID: $id</p>";
        echo "<p>Name: $name</p>";
        echo "<p>Type: $type</p>";
        echo "<p>$eatBehavior</p>";
        echo "<p>$soundBehavior</p>";
    } elseif ($action === 'remove') {
        $id = $_POST['remove-id'];

        // Delete the animal record based on the ID
        echo "<h1>Animal Record Deleted:</h1>";
        echo "<p>ID: $id</p>";
    }
}
?>

In this updated example, the HTML form includes three sections: one for adding an animal, one for editing an animal, and one for removing an animal. Each section has its own set of input fields and a hidden input field to identify the action to be performed.

The PHP code handles the form submission based on the action specified in the hidden input field. If the action is “add”, the appropriate animal object (Cat, Dog, or Bird) is created based on the selected type, and the eat and sound behaviors are performed and displayed. If the action is “edit”, the animal record is updated based on the selected type, and the updated behaviors and animal details are displayed. If the action is “remove”, the animal record is removed, and the corresponding animal ID is displayed.

This updated example provides the complete functionality for adding, editing, and removing animal records using PHP and a simple HTML form.

Task: 4

Build a PHP CRUD application for managing a contact list. Create a class called “Contact” with properties like name, email, and phone number. Implement methods to perform CRUD operations on the contact records in a database. Develop the user interface to display, add, update, and delete contacts.

HTML Form (index.html):

<!DOCTYPE html>
<html>
<head>
    <title>Contact List</title>
</head>
<body>
    <h1>Contact List</h1>

    <h2>Add Contact</h2>
    <form method="POST" action="process.php">
        <input type="hidden" name="action" value="add">

        <label for="name">Name:</label>
        <input type="text" name="name" required>

        <label for="email">Email:</label>
        <input type="email" name="email" required>

        <label for="phone">Phone:</label>
        <input type="text" name="phone" required>

        <input type="submit" name="submit" value="Add Contact">
    </form>

    <h2>Edit Contact</h2>
    <form method="POST" action="process.php">
        <input type="hidden" name="action" value="edit">

        <label for="edit-id">Contact ID:</label>
        <input type="number" name="edit-id" required>

        <label for="edit-name">Name:</label>
        <input type="text" name="edit-name" required>

        <label for="edit-email">Email:</label>
        <input type="email" name="edit-email" required>

        <label for="edit-phone">Phone:</label>
        <input type="text" name="edit-phone" required>

        <input type="submit" name="submit" value="Edit Contact">
    </form>

    <h2>Remove Contact</h2>
    <form method="POST" action="process.php">
        <input type="hidden" name="action" value="remove">

        <label for="remove-id">Contact ID:</label>
        <input type="number" name="remove-id" required>

        <input type="submit" name="submit" value="Remove Contact">
    </form>
</body>
</html>

PHP Code (process.php):

<?php
// Contact class
class Contact {
    private $id;
    private $name;
    private $email;
    private $phone;
    private $db; // Database connection

    public function __construct() {
        // Initialize the database connection
        $this->db = new PDO("mysql:host=localhost;dbname=your_database_name", "your_username", "your_password");
    }

    public function addContact($name, $email, $phone) {
        // Insert the contact record into the database
        $stmt = $this->db->prepare("INSERT INTO contacts (name, email, phone) VALUES (?, ?, ?)");
        $stmt->execute([$name, $email, $phone]);

        $this->id = $this->db->lastInsertId();
        $this->name = $name;
        $this->email = $email;
        $this->phone = $phone;
    }

    public function editContact($id, $name, $email, $phone) {
        // Update the contact record in the database
        $stmt = $this->db->prepare("UPDATE contacts SET name = ?, email = ?, phone = ? WHERE id = ?");
        $stmt->execute([$name, $email, $phone, $id]);

        $this->id = $id;
        $this->name = $name;
        $this->email = $email;
        $this->phone = $phone;
   }

    public function removeContact($id) {
        // Delete the contact record from the database
        $stmt = $this->db->prepare("DELETE FROM contacts WHERE id = ?");
        $stmt->execute([$id]);

        $this->id = null;
        $this->name = null;
        $this->email = null;
        $this->phone = null;
    }
}

// Process form submission
if (isset($_POST['submit'])) {
    $action = $_POST['action'];
    $contact = new Contact();

    if ($action === 'add') {
        $name = $_POST['name'];
        $email = $_POST['email'];
        $phone = $_POST['phone'];

        $contact->addContact($name, $email, $phone);

        // Redirect to the success page
        header("Location: success.html");
        exit();
    } elseif ($action === 'edit') {
        $id = $_POST['edit-id'];
        $name = $_POST['edit-name'];
        $email = $_POST['edit-email'];
        $phone = $_POST['edit-phone'];

        $contact->editContact($id, $name, $email, $phone);

        // Redirect to the success page
        header("Location: success.html");
        exit();
    } elseif ($action === 'remove') {
        $id = $_POST['remove-id'];

        $contact->removeContact($id);

        // Redirect to the success page
        header("Location: success.html");
        exit();
    }
}
?>

HTML Success Page (success.html):

<!DOCTYPE html>
<html>
<head>
    <title>Success</title>
</head>
<body>
    <h1>Action Completed Successfully</h1>
    <p>The requested action has been completed successfully.</p>
</body>
</html>

In this example, the HTML form includes three sections: one for adding a contact, one for editing a contact, and one for removing a contact. Each section has its own set of input fields and a hidden input field to identify the action to be performed.

The PHP code handles the form submission based on the action specified in the hidden input field. If the action is “add”, the addContact method is called to add the contact record to the database. If the action is “edit”, the editContact method is called to update the contact record. If the action is “remove”, the removeContact method is called to delete the contact record. After performing the respective action, the user is redirected to the success page (success.html).

The success page (success.html) displays a success message to indicate that the requested action has been completed successfully.

This example provides the complete functionality for adding, editing and removing contact records using PHP and a simple HTML form.

Task: 5

Task: Implement a class called “Product” with properties like name, price, and quantity. Build a PHP shopping cart system that allows users to add products to the cart, update quantities, and calculate the total price. Use the “Product” class to manage the products and implement the necessary functionality for the shopping cart.

HTML Form (index.html):

<!DOCTYPE html>
<html>
<head>
    <title>Shopping Cart</title>
</head>
<body>
    <h1>Shopping Cart</h1>

    <h2>Add Product</h2>
    <form method="POST" action="process.php">
        <input type="hidden" name="action" value="add">

        <label for="name">Product Name:</label>
        <input type="text" name="name" required>

        <label for="price">Price:</label>
        <input type="number" name="price" step="0.01" min="0" required>

        <label for="quantity">Quantity:</label>
        <input type="number" name="quantity" min="1" required>

        <input type="submit" name="submit" value="Add to Cart">
    </form>

    <h2>Edit Product Quantity</h2>
    <form method="POST" action="process.php">
        <input type="hidden" name="action" value="edit">

        <label for="edit-id">Product ID:</label>
        <input type="number" name="edit-id" required>

        <label for="edit-quantity">New Quantity:</label>
        <input type="number" name="edit-quantity" min="1" required>

        <input type="submit" name="submit" value="Update Quantity">
    </form>

    <h2>Remove Product</h2>
    <form method="POST" action="process.php">
        <input type="hidden" name="action" value="remove">

        <label for="remove-id">Product ID:</label>
        <input type="number" name="remove-id" required>

        <input type="submit" name="submit" value="Remove Product">
    </form>
</body>
</html>

PHP Code (process.php):

<?php
// Product class
class Product {
    private $id;
    private $name;
    private $price;
    private $quantity;

    public function __construct($name, $price, $quantity) {
        $this->id = uniqid();
        $this->name = $name;
        $this->price = $price;
        $this->quantity = $quantity;
    }

    public function getId() {
        return $this->id;
    }

    public function getName() {
        return $this->name;
    }

    public function getPrice() {
        return $this->price;
    }

    public function getQuantity() {
        return $this->quantity;
    }
}

session_start();

// Check if the shopping cart exists in the session
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = [];
}

// Process form submission
if (isset($_POST['submit'])) {
    $action = $_POST['action'];

    if ($action === 'add') {
        $name = $_POST['name'];
        $price = $_POST['price'];
        $quantity = $_POST['quantity'];

        $product = new Product($name, $price, $quantity);

        // Add the product to the shopping cart
        array_push($_SESSION['cart'], $product);

        // Redirect to the success page
        header("Location: success.html");
        exit();
    } elseif ($action === 'edit') {
        $id = $_POST['edit-id'];
        $newQuantity = $_POST['edit-quantity'];

        // Find the product in the shopping cart based on the ID
        foreach ($_SESSION['cart'] as $product) {
            if ($product->getId() === $id) {
                // Update the product's quantity
                $product->quantity = $newQuantity;
                break;
            }
        }

        // Redirect to the success page
        header("Location: success.html");
        exit();
    } elseif ($action === 'remove') {
        $id = $_POST['remove-id'];

        // Find the product in the shopping cart based on the ID and remove it
        foreach ($_SESSION['cart'] as $key => $product) {
            if ($product->getId() === $id) {
                unset($_SESSION['cart'][$key]);
                break;
            }
        }

        // Re-index the shopping cart array
        $_SESSION['cart'] = array_values($_SESSION['cart']);

        // Redirect to the success page
        header("Location: success.html");
        exit();
    }
}
?>

PHP Code (process.php):

<?php
// Product class
class Product {
    private $id;
    private $name;
    private $price;
    private $quantity;

    public function __construct($name, $price, $quantity) {
        $this->id = uniqid();
        $this->name = $name;
        $this->price = $price;
        $this->quantity = $quantity;
    }

    public function getId() {
        return $this->id;
    }

    public function getName() {
        return $this->name;
    }

    public function getPrice() {
        return $this->price;
    }

    public function getQuantity() {
        return $this->quantity;
    }
}

session_start();

// Check if the shopping cart exists in the session
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = [];
}

// Process form submission
if (isset($_POST['submit'])) {
    $action = $_POST['action'];

    if ($action === 'add') {
        $name = $_POST['name'];
        $price = $_POST['price'];
        $quantity = $_POST['quantity'];

        $product = new Product($name, $price, $quantity);

        // Add the product to the shopping cart
        array_push($_SESSION['cart'], $product);

        // Redirect to the success page
        header("Location: success.html");
        exit();
    } elseif ($action === 'edit') {
        $id = $_POST['edit-id'];
        $newQuantity = $_POST['edit-quantity'];

        // Find the product in the shopping cart based on the ID
        foreach ($_SESSION['cart'] as $product) {
            if ($product->getId() === $id) {
                // Update the product's quantity
                $product->quantity = $newQuantity;
                break;
            }
        }

        // Redirect to the success page
        header("Location: success.html");
        exit();
    } elseif ($action === 'remove') {
        $id = $_POST['remove-id'];

        // Find the product in the shopping cart based on the ID and remove it
        foreach ($_SESSION['cart'] as $key => $product) {
            if ($product->getId() === $id) {
                unset($_SESSION['cart'][$key]);
                break;
            }
        }

        // Re-index the shopping cart array
        $_SESSION['cart'] = array_values($_SESSION['cart']);

        // Redirect to the success page
        header("Location: success.html");
        exit();
    }
}
?>

HTML Success Page (success.html):

<!DOCTYPE html>
<html>
<head>
    <title>Success</title>
</head>
<body>
    <h1>Action Completed Successfully</h1>
    <p>The requested action has been completed successfully.</p>
</body>
</html>

In this example, the HTML form includes three sections: one for adding a product to the shopping cart, one for editing the quantity of a product in the cart, and one for removing a product from the cart. Each section has its own set of input fields and a hidden input field to identify the action to be performed.

The PHP code processes the form submission based on the action specified in the hidden input field. If the action is “add”, a new Product object is created with the provided name, price, and quantity, and it is added to the shopping cart stored in the session. If the action is “edit”, the quantity of a product in the cart is updated based on the provided ID. If the action is “remove”, a product is removed from the cart based on the provided ID. After performing the respective action, the user is redirected to the success page (success.html).

The success page (success.html) displays a success message to indicate that the requested action has been completed successfully.

This example provides the complete functionality for adding, editing, and removing products in a shopping cart using PHP and a simple HTML form. The shopping cart data is stored in the session to maintain its state across different requests.

Leave a Comment