Author: admin

  • Lesson 19: Introduction to PHP Frameworks

    PHP frameworks streamline development by providing tools, libraries, and best practices to build robust, secure, and scalable applications. This lesson introduces popular PHP frameworks, including Laravel, Symfony, and CodeIgniter, and provides a detailed guide to installing and setting up Laravel.


    19.1 Overview of PHP Frameworks

    What is a PHP Framework?

    • A PHP framework is a platform that provides a structured way to build PHP applications.
    • Benefits:
      • Simplifies repetitive tasks like routing, authentication, and database management.
      • Encourages clean, reusable code.
      • Enhances application security and scalability.

    Popular PHP Frameworks

    1. Laravel

    • Tagline: “The PHP Framework for Web Artisans.”
    • Features:
      • Elegant syntax and expressive ORM (Eloquent).
      • Built-in authentication and authorization.
      • Blade templating engine for views.
      • Easy database migrations.
      • Integrated task scheduling and queue system.
    • Use Cases:
      • Ideal for medium to large-scale applications requiring complex features.

    2. Symfony

    • Tagline: “A set of reusable PHP components and a framework for web applications.”
    • Features:
      • Modular components (e.g., Symfony HTTP Foundation, Security).
      • High performance and flexibility.
      • Advanced configuration options.
      • Used as a foundation for other frameworks like Laravel.
    • Use Cases:
      • Suitable for enterprise-level applications with specific requirements.

    3. CodeIgniter

    • Tagline: “A powerful PHP framework with a very small footprint.”
    • Features:
      • Lightweight and fast.
      • Simple and straightforward.
      • No complex configurations or dependencies.
      • Excellent for building REST APIs and small-scale applications.
    • Use Cases:
      • Best for small to medium-sized projects or developers new to frameworks.

    Comparison Table

    Feature Laravel Symfony CodeIgniter
    Learning Curve Moderate Steep Easy
    Scalability High Very High Moderate
    Performance Moderate High Very High
    Community Support Large and active Active Moderate
    Templating Engine Blade Twig Basic PHP

    19.2 Installing and Setting Up Laravel

    Step 1: System Requirements

    Before installing Laravel, ensure your system meets the following requirements:

    • PHP: Version 8.0 or higher.
    • Composer: Dependency manager for PHP.
    • Database: MySQL, PostgreSQL, SQLite, or SQL Server.

    Step 2: Installing Composer

    1. Download and install Composer from getcomposer.org.
    2. Verify installation:
      bash
      composer --version

    Step 3: Installing Laravel

    Laravel can be installed in two ways: via the Laravel Installer or Composer.

    Method 1: Using Laravel Installer

    1. Install the Laravel Installer:
      bash
      composer global require laravel/installer
    2. Create a new Laravel project:
      bash
      laravel new project-name
    3. Navigate to the project directory:
      bash
      cd project-name

    Method 2: Using Composer

    1. Run the following command:
      bash
      composer create-project --prefer-dist laravel/laravel project-name
    2. Navigate to the project directory:
      bash
      cd project-name

    Step 4: Setting Up the Development Environment

    1. Environment Configuration:
      • Rename .env.example to .env:
        bash
        cp .env.example .env
      • Configure database settings in the .env file:
        env
        DB_CONNECTION=mysql
        DB_HOST=127.0.0.1
        DB_PORT=3306
        DB_DATABASE=your_database_name
        DB_USERNAME=your_database_username
        DB_PASSWORD=your_database_password
    2. Generate Application Key:
      bash
      php artisan key:generate
      • This command sets the APP_KEY in the .env file, which is used for encryption.

    Step 5: Running the Application

    1. Start the development server:
      bash
      php artisan serve
    2. Open your browser and navigate to:
      text
      http://localhost:8000

    Step 6: Exploring Laravel Directory Structure

    • app/: Contains the core application files (models, controllers, etc.).
    • routes/: Contains route definitions (web.php for web routes, api.php for API routes).
    • resources/views/: Stores Blade templates for views.
    • database/: Contains migration and seed files.
    • public/: Entry point for the application (e.g., index.php).

    19.3 Creating a Simple Laravel Application

    Example: Task Management Application

    Step 1: Set Up the Database

    1. Create a database tasks.
    2. Update the .env file:
      env
      DB_DATABASE=tasks

    Step 2: Create a Migration

    1. Run the migration command:
      bash
      php artisan make:migration create_tasks_table
    2. Edit the migration file in database/migrations/:
      php
      public function up()
      {
      Schema::create('tasks', function (Blueprint $table) {
      $table->id();
      $table->string('title');
      $table->boolean('completed')->default(false);
      $table->timestamps();
      });
      }
    3. Run the migration:
      bash
      php artisan migrate

    Step 3: Create a Model

    1. Run the model command:
      bash
      php artisan make:model Task

    Step 4: Create a Controller

    1. Run the controller command:
      bash
      php artisan make:controller TaskController
    2. Add the following methods to TaskController:
      php
      public function index()
      {
      $tasks = Task::all();
      return view('tasks.index', compact('tasks'));
      }
      public function store(Request $request)
      {
      $task = new Task();
      $task->title = $request->title;
      $task->save();

      return redirect()->back();
      }


    Step 5: Set Up Routes

    Edit routes/web.php:

    php

    use App\Http\Controllers\TaskController;

    Route::get(‘/’, [TaskController::class, ‘index’]);
    Route::post(‘/tasks’, [TaskController::class, ‘store’]);


    Step 6: Create a Blade Template

    Create a new file resources/views/tasks/index.blade.php:

    html
    <!DOCTYPE html>
    <html>
    <head>
    <title>Task Manager</title>
    </head>
    <body>
    <h1>Task Manager</h1>
    <form action="/tasks" method="POST">
    @csrf
    <input type="text" name="title" placeholder="New Task" required>
    <button type="submit">Add Task</button>
    </form>
    <ul>
    @foreach ($tasks as $task)
    <li>{{ $task->title }}</li>
    @endforeach
    </ul>
    </body>
    </html>


    Activities and Exercises

    1. Explore Laravel Features:
      • Experiment with database migrations, routes, and Blade templates.
    2. Build a Simple Application:
      • Create a “Contact Manager” application with CRUD operations for contacts.
    3. Experiment with Middleware:
      • Add middleware for authentication or logging requests.

    Assignment

    1. Create a “Blog” application with the following features:
      • Display a list of blog posts.
      • Add new posts.
      • Edit and delete existing posts.
    2. Explore the official Laravel documentation to learn about:
      • Authentication (php artisan make:auth).
      • Laravel’s built-in queue system.

    Summary

    In this lesson, you learned:

    1. The benefits and features of Laravel, Symfony, and CodeIgniter.
    2. How to install and set up Laravel.
    3. How to create a simple Laravel application.

    Laravel provides a powerful foundation for building modern PHP applications. Let me know if you’d like to dive deeper into Laravel or other frameworks!

  • Lesson 18: Email Handling in PHP

    Sending emails is a fundamental feature in web applications for purposes like user verification, notifications, and newsletters. This lesson will guide you through sending emails using PHPMailer and handling email attachments.


    18.1 Introduction to PHPMailer

    What is PHPMailer?

    • PHPMailer is a popular library for sending emails in PHP.
    • Why Use PHPMailer?
      • Provides a simple interface for sending emails.
      • Supports advanced features like attachments, HTML emails, and SMTP authentication.
      • Handles complex email tasks that are cumbersome with PHP’s native mail() function.

    18.2 Installing PHPMailer

    Step 1: Install via Composer

    1. Open your project directory in the terminal.
    2. Run the following command:
      bash
      composer require phpmailer/phpmailer

    Step 2: Include PHPMailer in Your Script

    php
    require 'vendor/autoload.php';
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;

    18.3 Sending Basic Emails with PHPMailer

    Example: Sending a Simple Email

    php
    <?php
    require 'vendor/autoload.php';
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;

    $mail = new PHPMailer(true);

    try {
    // Server settings
    $mail->isSMTP();
    $mail->Host = ‘smtp.gmail.com’; // SMTP server
    $mail->SMTPAuth = true;
    $mail->Username = ‘your-email@gmail.com’; // Your email
    $mail->Password = ‘your-email-password’; // Your email password or app password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;

    // Recipients
    $mail->setFrom(‘your-email@gmail.com’, ‘Your Name’);
    $mail->addAddress(‘recipient@example.com’, ‘Recipient Name’);

    // Content
    $mail->isHTML(true); // Set email format to HTML
    $mail->Subject = ‘Test Email from PHPMailer’;
    $mail->Body = ‘<h1>Hello!</h1><p>This is a test email sent using PHPMailer.</p>’;
    $mail->AltBody = ‘This is a plain-text version of the email content.’;

    // Send the email
    $mail->send();
    echo ‘Email has been sent successfully.’;
    } catch (Exception $e) {
    echo “Email could not be sent. Mailer Error: {$mail->ErrorInfo};
    }
    ?>


    18.4 Handling Email Attachments

    Adding Attachments

    Use the addAttachment() method to include files in your email.

    Example: Sending an Email with Attachments

    php
    <?php
    require 'vendor/autoload.php';
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;

    $mail = new PHPMailer(true);

    try {
    // Server settings
    $mail->isSMTP();
    $mail->Host = ‘smtp.gmail.com’;
    $mail->SMTPAuth = true;
    $mail->Username = ‘your-email@gmail.com’;
    $mail->Password = ‘your-email-password’;
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;

    // Recipients
    $mail->setFrom(‘your-email@gmail.com’, ‘Your Name’);
    $mail->addAddress(‘recipient@example.com’, ‘Recipient Name’);

    // Attachments
    $mail->addAttachment(‘path/to/file.txt’); // Attach a file
    $mail->addAttachment(‘path/to/image.jpg’, ‘CustomName.jpg’); // Attach with a custom name

    // Content
    $mail->isHTML(true);
    $mail->Subject = ‘Email with Attachments’;
    $mail->Body = ‘<p>Please find the attached files.</p>’;

    // Send the email
    $mail->send();
    echo ‘Email with attachments has been sent successfully.’;
    } catch (Exception $e) {
    echo “Email could not be sent. Mailer Error: {$mail->ErrorInfo};
    }
    ?>


    18.5 Sending Emails from an HTML Form

    HTML Form

    Create a file email_form.html:

    html
    <form action="send_email.php" method="POST" enctype="multipart/form-data">
    <label for="email">Recipient Email:</label>
    <input type="email" name="email" id="email" required><br>
    <label for=“subject”>Subject:</label>
    <input type=“text” name=“subject” id=“subject” required><br>

    <label for=“message”>Message:</label>
    <textarea name=“message” id=“message” required></textarea><br>

    <label for=“attachment”>Attachment:</label>
    <input type=“file” name=“attachment” id=“attachment”><br>

    <button type=“submit”>Send Email</button>
    </form>


    Handling the Form Submission

    Create a file send_email.php:

    php
    <?php
    require 'vendor/autoload.php';
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;

    $mail = new PHPMailer(true);

    try {
    // Retrieve form data
    $recipient = $_POST[’email’];
    $subject = $_POST[‘subject’];
    $message = $_POST[‘message’];

    // Server settings
    $mail->isSMTP();
    $mail->Host = ‘smtp.gmail.com’;
    $mail->SMTPAuth = true;
    $mail->Username = ‘your-email@gmail.com’;
    $mail->Password = ‘your-email-password’;
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;

    // Recipients
    $mail->setFrom(‘your-email@gmail.com’, ‘Your Name’);
    $mail->addAddress($recipient);

    // Check and attach file
    if (isset($_FILES[‘attachment’]) && $_FILES[‘attachment’][‘error’] == UPLOAD_ERR_OK) {
    $mail->addAttachment($_FILES[‘attachment’][‘tmp_name’], $_FILES[‘attachment’][‘name’]);
    }

    // Content
    $mail->isHTML(true);
    $mail->Subject = $subject;
    $mail->Body = $message;

    // Send the email
    $mail->send();
    echo ‘Email has been sent successfully.’;
    } catch (Exception $e) {
    echo “Email could not be sent. Mailer Error: {$mail->ErrorInfo};
    }
    ?>


    18.6 Practical Example: Newsletter System

    Steps:

    1. Database Setup:
      • Create a table subscribers:
        sql
        CREATE TABLE subscribers (
        id INT AUTO_INCREMENT PRIMARY KEY,
        email VARCHAR(100) NOT NULL UNIQUE,
        subscribed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        );
    2. Subscribe Form:
      html
      <form action="subscribe.php" method="POST">
      <label for="email">Email:</label>
      <input type="email" name="email" id="email" required>
      <button type="submit">Subscribe</button>
      </form>
    3. Handle Subscription:
      php
      <?php
      require 'db.php'; // Include your database connection
      if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
      $email = $_POST[’email’];
      $stmt = $conn->prepare(“INSERT INTO subscribers (email) VALUES (:email)”);
      $stmt->bindParam(‘:email’, $email);

      if ($stmt->execute()) {
      echo “Thank you for subscribing!”;
      } else {
      echo “Error: Could not subscribe.”;
      }
      }
      ?>

    4. Send Newsletter: Create a script to send newsletters to all subscribers:
      php
      <?php
      require 'vendor/autoload.php';
      require 'db.php';
      $mail = new PHPMailer(true);

      try {
      // Fetch all subscribers
      $stmt = $conn->query(“SELECT email FROM subscribers”);
      $subscribers = $stmt->fetchAll(PDO::FETCH_ASSOC);

      // Server settings
      $mail->isSMTP();
      $mail->Host = ‘smtp.gmail.com’;
      $mail->SMTPAuth = true;
      $mail->Username = ‘your-email@gmail.com’;
      $mail->Password = ‘your-email-password’;
      $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
      $mail->Port = 587;

      // Sender
      $mail->setFrom(‘your-email@gmail.com’, ‘Your Name’);

      // Email content
      $mail->isHTML(true);
      $mail->Subject = ‘Newsletter’;
      $mail->Body = ‘<p>This is the latest newsletter.</p>’;

      foreach ($subscribers as $subscriber) {
      $mail->addAddress($subscriber[’email’]);
      $mail->send();
      $mail->clearAddresses(); // Clear recipient for next iteration
      }

      echo “Newsletter sent successfully.”;
      } catch (Exception $e) {
      echo “Error: {$mail->ErrorInfo};
      }
      ?>


    Activities and Exercises

    1. Basic Email:
      • Write a script to send a plain-text email to multiple recipients.
    2. Attachments:
      • Allow multiple attachments in an email form.
    3. Newsletter System:
      • Create a system that allows users to unsubscribe.

    Assignment

    1. Build a file-sharing system:
      • Users upload files, and the system emails the file as an attachment to a specified recipient.
    2. Create an email reminder system:
      • Send automated emails to users reminding them of pending tasks from a tasks database.

    Summary

    In this lesson, you learned:

    1. How to send emails using PHPMailer.
    2. How to handle email attachments.
    3. How to integrate email functionality into dynamic PHP applications.

    These skills are essential for creating email-driven features like newsletters, notifications, and file sharing. Let me know if you’d like more examples or exercises!

  • Lesson 17: PHP and APIs

    APIs (Application Programming Interfaces) allow systems to communicate with each other. RESTful APIs are widely used in web applications to exchange data. In this lesson, you will learn how to consume RESTful APIs and build a simple REST API using PHP.


    Lesson Outline

    1. Introduction to RESTful APIs
    2. Consuming RESTful APIs
    3. Building a Simple REST API with PHP

    17.1 Introduction to RESTful APIs

    What is a RESTful API?

    • REST (Representational State Transfer) is an architectural style for designing APIs.
    • Key Features:
      • Stateless: Each request is independent and contains all necessary information.
      • HTTP Methods: Standard HTTP methods are used for CRUD operations:
        • GET: Retrieve data.
        • POST: Create data.
        • PUT: Update data.
        • DELETE: Delete data.
      • Resource-based: Data is represented as resources (e.g., /users, /products).

    17.2 Consuming RESTful APIs

    Fetching Data with file_get_contents

    Example: Fetching Data from a Public API

    php
    <?php
    $url = "https://jsonplaceholder.typicode.com/posts";
    $response = file_get_contents($url);
    $data = json_decode($response, true); // Decode JSON response into an array
    foreach ($data as $post) {
    echo “Title: “ . $post[‘title’] . “<br>”;
    echo “Body: “ . $post[‘body’] . “<hr>”;
    }
    ?>


    Using cURL to Consume APIs

    What is cURL?

    • cURL is a library in PHP for making HTTP requests.

    GET Request with cURL

    php
    <?php
    $url = "https://jsonplaceholder.typicode.com/posts";
    $ch = curl_init($url); // Initialize cURL
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string
    $response = curl_exec($ch); // Execute the request
    curl_close($ch); // Close cURL

    $data = json_decode($response, true); // Decode JSON response

    foreach ($data as $post) {
    echo “Title: “ . $post[‘title’] . “<br>”;
    echo “Body: “ . $post[‘body’] . “<hr>”;
    }
    ?>


    POST Request with cURL

    php
    <?php
    $url = "https://jsonplaceholder.typicode.com/posts";
    $data = [
    'title' => 'New Post',
    'body' => 'This is the content of the post.',
    'userId' => 1
    ];
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
    ‘Content-Type: application/json’,
    ‘Content-Length: ‘ . strlen(json_encode($data))
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    echo “Response: “ . $response;
    ?>


    17.3 Building a Simple REST API with PHP

    Setting Up the Environment

    1. Create a new database api_demo and a table users:
      sql

      CREATE DATABASE api_demo;

      USE api_demo;

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

    2. Insert sample data:
      sql
      INSERT INTO users (name, email) VALUES
      ('Alice', 'alice@example.com'),
      ('Bob', 'bob@example.com');
    3. Create a file db.php for database connection:
      php
      <?php
      $host = "localhost";
      $username = "root";
      $password = "";
      $database = "api_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());
      }
      ?>


    Creating the REST API

    Step 1: API Endpoint Structure

    • /api/users – GET (Retrieve all users)
    • /api/users/:id – GET (Retrieve a specific user)
    • /api/users – POST (Create a new user)
    • /api/users/:id – PUT (Update a user)
    • /api/users/:id – DELETE (Delete a user)

    Step 2: Base API File (api.php)

    php
    <?php
    require 'db.php';
    header(“Content-Type: application/json”);

    $requestMethod = $_SERVER[“REQUEST_METHOD”];
    $requestUri = explode(“/”, trim($_SERVER[“REQUEST_URI”], “/”));

    // Extract resource and ID
    $resource = $requestUri[1] ?? null;
    $id = $requestUri[2] ?? null;

    if ($resource !== ‘users’) {
    http_response_code(404);
    echo json_encode([‘message’ => ‘Resource not found’]);
    exit;
    }
    ?>


    Step 3: Handle GET Requests

    php
    if ($requestMethod === 'GET') {
    if ($id) {
    $stmt = $conn->prepare("SELECT * FROM users WHERE id = :id");
    $stmt->bindParam(':id', $id);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($user) {
    echo json_encode($user);
    } else {
    http_response_code(404);
    echo json_encode([‘message’ => ‘User not found’]);
    }
    } else {
    $stmt = $conn->query(“SELECT * FROM users”);
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($users);
    }
    }


    Step 4: Handle POST Requests

    php
    if ($requestMethod === 'POST') {
    $data = json_decode(file_get_contents("php://input"), true);
    $stmt = $conn->prepare(“INSERT INTO users (name, email) VALUES (:name, :email)”);
    $stmt->bindParam(‘:name’, $data[‘name’]);
    $stmt->bindParam(‘:email’, $data[’email’]);

    if ($stmt->execute()) {
    http_response_code(201);
    echo json_encode([‘message’ => ‘User created’]);
    } else {
    http_response_code(500);
    echo json_encode([‘message’ => ‘Error creating user’]);
    }
    }


    Step 5: Handle PUT Requests

    php
    if ($requestMethod === 'PUT' && $id) {
    $data = json_decode(file_get_contents("php://input"), true);
    $stmt = $conn->prepare(“UPDATE users SET name = :name, email = :email WHERE id = :id”);
    $stmt->bindParam(‘:id’, $id);
    $stmt->bindParam(‘:name’, $data[‘name’]);
    $stmt->bindParam(‘:email’, $data[’email’]);

    if ($stmt->execute()) {
    echo json_encode([‘message’ => ‘User updated’]);
    } else {
    http_response_code(500);
    echo json_encode([‘message’ => ‘Error updating user’]);
    }
    }


    Step 6: Handle DELETE Requests

    php
    if ($requestMethod === 'DELETE' && $id) {
    $stmt = $conn->prepare("DELETE FROM users WHERE id = :id");
    $stmt->bindParam(':id', $id);
    if ($stmt->execute()) {
    echo json_encode([‘message’ => ‘User deleted’]);
    } else {
    http_response_code(500);
    echo json_encode([‘message’ => ‘Error deleting user’]);
    }
    }


    Testing the API

    1. Use tools like Postman or cURL to test API endpoints.
    2. Example cURL commands:
      • GET all users:
        bash
        curl -X GET http://localhost/api/users
      • POST a new user:
        bash
        curl -X POST -H "Content-Type: application/json" -d '{"name":"Charlie","email":"charlie@example.com"}' http://localhost/api/users

    Activities and Exercises

    1. Consuming APIs:
      • Fetch and display posts from the JSONPlaceholder API using cURL.
    2. Building APIs:
      • Extend the users API to include user authentication (e.g., login).
    3. Validation:
      • Add validation for user input (e.g., email format, required fields) in the POST and PUT endpoints.

    Assignment

    1. Create a database library with tables:
      • books: id, title, author.
      • users: id, name, email.
      • borrowed_books: id, user_id, book_id, borrowed_at.
    2. Build an API with the following endpoints:
      • /api/books (GET): Retrieve all books.
      • /api/users/:id/borrowed (GET): Retrieve books borrowed by a user.
      • /api/borrow (POST): Borrow a book.
  • Lesson 16: Working with Files

    In this lesson, you’ll learn how to manage files in PHP. We’ll cover reading and writing files, as well as handling file uploads, which are common tasks in dynamic web applications.


    16.1 Reading and Writing Files

    Introduction to File Handling

    PHP provides several functions to read, write, and manage files:

    1. fopen(): Opens a file for reading, writing, or appending.
    2. fclose(): Closes an open file.
    3. fwrite(): Writes data to a file.
    4. fread(): Reads data from a file.
    5. file_get_contents(): Reads the entire file content as a string.
    6. file_put_contents(): Writes data to a file, overwriting or appending.

    Reading Files

    Example: Reading File Contents

    php
    <?php
    $file = "example.txt";
    // Check if the file exists
    if (file_exists($file)) {
    $content = file_get_contents($file);
    echo “File Content:<br>”;
    echo nl2br($content); // Converts newlines to <br> for HTML
    } else {
    echo “File not found.”;
    }
    ?>

    Example: Reading Line by Line

    php
    <?php
    $file = "example.txt";
    if (file_exists($file)) {
    $handle = fopen($file, “r”); // Open file for reading
    while (($line = fgets($handle)) !== false) {
    echo $line . “<br>”;
    }
    fclose($handle); // Close the file
    } else {
    echo “File not found.”;
    }
    ?>


    Writing Files

    Example: Writing to a File

    php
    <?php
    $file = "example.txt";
    $content = "This is a sample content written to the file.";
    if ($handle = fopen($file, “w”)) { // Open file for writing
    fwrite($handle, $content);
    fclose($handle);
    echo “File written successfully.”;
    } else {
    echo “Unable to write to the file.”;
    }
    ?>

    Appending to a File

    php
    <?php
    $file = "example.txt";
    $content = "This is an additional line.";
    if ($handle = fopen($file, “a”)) { // Open file for appending
    fwrite($handle, $content . PHP_EOL); // PHP_EOL adds a newline
    fclose($handle);
    echo “Content appended successfully.”;
    } else {
    echo “Unable to append to the file.”;
    }
    ?>


    Deleting Files

    php
    <?php
    $file = "example.txt";
    if (file_exists($file)) {
    unlink($file); // Deletes the file
    echo “File deleted successfully.”;
    } else {
    echo “File does not exist.”;
    }
    ?>


    16.2 File Uploads

    How File Uploads Work

    1. A file is selected and submitted via an HTML form.
    2. PHP handles the uploaded file using the $_FILES superglobal.
    3. You can validate the file size, type, and name before saving it to the server.

    Setting Up a File Upload Form

    HTML Form

    html
    <form action="upload.php" method="POST" enctype="multipart/form-data">
    <label for="file">Choose a file:</label>
    <input type="file" name="file" id="file" required>
    <button type="submit">Upload</button>
    </form>

    Handling File Uploads in PHP

    Basic File Upload Script

    php
    <?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $uploadDir = "uploads/"; // Directory where files will be uploaded
    $uploadFile = $uploadDir . basename($_FILES["file"]["name"]);
    // Move the uploaded file to the desired directory
    if (move_uploaded_file($_FILES[“file”][“tmp_name”], $uploadFile)) {
    echo “File uploaded successfully: “ . htmlspecialchars(basename($_FILES[“file”][“name”]));
    } else {
    echo “Error uploading the file.”;
    }
    }
    ?>


    Validating Uploaded Files

    Check File Size

    php
    if ($_FILES["file"]["size"] > 2000000) { // Limit file size to 2MB
    die("Error: File size exceeds 2MB.");
    }

    Check File Type

    php

    $allowedTypes = ["image/jpeg", "image/png", "application/pdf"];

    if (!in_array($_FILES[“file”][“type”], $allowedTypes)) {
    die(“Error: Unsupported file type.”);
    }


    Improved File Upload Script

    php
    <?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $uploadDir = "uploads/";
    $fileName = basename($_FILES["file"]["name"]);
    $uploadFile = $uploadDir . $fileName;
    // File validation
    if ($_FILES[“file”][“size”] > 2000000) {
    die(“Error: File size exceeds 2MB.”);
    }

    $allowedTypes = [“image/jpeg”, “image/png”, “application/pdf”];
    if (!in_array($_FILES[“file”][“type”], $allowedTypes)) {
    die(“Error: Unsupported file type.”);
    }

    // Upload the file
    if (move_uploaded_file($_FILES[“file”][“tmp_name”], $uploadFile)) {
    echo “File uploaded successfully: “ . htmlspecialchars($fileName);
    } else {
    echo “Error uploading the file.”;
    }
    }
    ?>


    Display Uploaded Files

    php
    <?php
    $uploadDir = "uploads/";
    $files = scandir($uploadDir);
    echo “<h3>Uploaded Files:</h3>”;
    foreach ($files as $file) {
    if ($file !== “.” && $file !== “..”) {
    echo “<a href=’$uploadDir$file‘>$file</a><br>”;
    }
    }
    ?>


    Practical Example

    File Management System

    1. Create a folder called uploads in your project directory.
    2. Implement the following features:
      • A form to upload files.
      • A script to list all uploaded files with download links.
      • A delete button next to each file to remove it from the server.

    Activities and Exercises

    1. File Reading:
      • Write a script to read and display the content of a .txt file.
      • Count the number of lines in the file.
    2. File Writing:
      • Create a script to log user activity in a log file (activity.log) with timestamps.
    3. File Upload:
      • Create a file upload form that accepts only .jpg and .png files and rejects others.
    4. File Management:
      • Implement a file browser that allows users to upload, view, and delete files.

    Assignment

    1. Create a PHP script that:
      • Allows users to upload files.
      • Validates file size (max 5MB) and type (only .pdf and .docx).
      • Stores the uploaded files in a directory named documents.
    2. Extend the script to:
      • Display all uploaded files in a table with options to:
        • Download the file.
        • Delete the file.

    Summary

    In this lesson, you learned:

    1. How to read and write files in PHP.
    2. How to handle file uploads securely.
    3. How to validate file size and type to ensure safe uploads.

    These skills are essential for managing files in dynamic PHP applications. Let me know if you need further clarification or examples!

  • Lesson 15: Advanced Database Operations

    In this lesson, you’ll learn advanced techniques for working with databases in PHP, including prepared statements for security, transactions for managing complex operations, and joins for querying related data from multiple tables.


    15.1 Prepared Statements

    What are Prepared Statements?

    • A prepared statement is a precompiled SQL query that separates query structure from data values.
    • Advantages:
      • Prevents SQL injection.
      • Improves performance when running the same query multiple times.

    Syntax for Prepared Statements

    php
    $stmt = $conn->prepare("SQL_QUERY");
    $stmt->bindParam(':param', $value);
    $stmt->execute();

    Example: Prepared Statement with PDO

    Insert Data

    php
    <?php
    require 'db.php';
    $name = “Alice”;
    $email = “alice@example.com”;

    $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.”;
    }
    ?>

    Select Data

    php
    <?php
    $stmt = $conn->prepare("SELECT * FROM users WHERE email = :email");
    $email = "alice@example.com";
    $stmt->bindParam(':email', $email);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($user) {
    echo “Name: “ . $user[‘name’] . “, Email: “ . $user[’email’];
    } else {
    echo “No user found.”;
    }
    ?>

    Update Data

    php
    <?php
    $stmt = $conn->prepare("UPDATE users SET name = :name WHERE email = :email");
    $name = "Alice Updated";
    $email = "alice@example.com";
    $stmt->bindParam(':name', $name);
    $stmt->bindParam(':email', $email);
    if ($stmt->execute()) {
    echo “User updated successfully.”;
    } else {
    echo “Error updating user.”;
    }
    ?>

    Delete Data

    php
    <?php
    $stmt = $conn->prepare("DELETE FROM users WHERE email = :email");
    $email = "alice@example.com";
    $stmt->bindParam(':email', $email);
    if ($stmt->execute()) {
    echo “User deleted successfully.”;
    } else {
    echo “Error deleting user.”;
    }
    ?>


    15.2 Transactions

    What is a Transaction?

    • A transaction is a series of SQL queries executed as a single unit of work.
    • Transactions ensure data integrity by following ACID principles:
      • Atomicity: All operations succeed or none.
      • Consistency: Database remains in a valid state.
      • Isolation: Transactions do not interfere with each other.
      • Durability: Changes persist even after a crash.

    Transaction Control Commands

    • Begin Transaction: Starts a transaction.
    • Commit: Saves all changes.
    • Rollback: Reverts changes if an error occurs.

    Example: Using Transactions in PDO

    Transfer Funds

    php
    <?php
    require 'db.php';
    try {
    $conn->beginTransaction();

    // Deduct from sender’s account
    $stmt = $conn->prepare(“UPDATE accounts SET balance = balance – :amount WHERE id = :sender_id”);
    $stmt->execute([‘:amount’ => 100, ‘:sender_id’ => 1]);

    // Add to receiver’s account
    $stmt = $conn->prepare(“UPDATE accounts SET balance = balance + :amount WHERE id = :receiver_id”);
    $stmt->execute([‘:amount’ => 100, ‘:receiver_id’ => 2]);

    $conn->commit();
    echo “Transaction completed successfully.”;
    } catch (Exception $e) {
    $conn->rollBack();
    echo “Transaction failed: “ . $e->getMessage();
    }
    ?>


    15.3 Joins

    What are Joins?

    • Joins combine rows from two or more tables based on related columns.
    • Types of Joins:
      1. Inner Join: Returns matching rows from both tables.
      2. Left Join: Returns all rows from the left table and matching rows from the right table.
      3. Right Join: Returns all rows from the right table and matching rows from the left table.
      4. Full Outer Join: Returns all rows from both tables.

    Example: Joins

    Database Setup

    Create two tables, users and orders:

    sql
    CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50),
    email VARCHAR(100)
    );
    CREATE TABLE orders (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT,
    product VARCHAR(50),
    amount DECIMAL(10, 2),
    FOREIGN KEY (user_id) REFERENCES users(id)
    );

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

    INSERT INTO orders (user_id, product, amount) VALUES
    (1, ‘Laptop’, 1500),
    (1, ‘Mouse’, 20),
    (2, ‘Keyboard’, 50);


    Inner Join

    Retrieve all users with their orders:

    php
    <?php
    $stmt = $conn->query("
    SELECT users.name, orders.product, orders.amount
    FROM users
    INNER JOIN orders ON users.id = orders.user_id
    "
    );
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo “Name: “ . $row[‘name’] . “, Product: “ . $row[‘product’] . “, Amount: “ . $row[‘amount’] . “<br>”;
    }
    ?>

    Output:

    yaml
    Name: Alice, Product: Laptop, Amount: 1500
    Name: Alice, Product: Mouse, Amount: 20
    Name: Bob, Product: Keyboard, Amount: 50

    Left Join

    Retrieve all users, including those without orders:

    php
    <?php
    $stmt = $conn->query("
    SELECT users.name, orders.product, orders.amount
    FROM users
    LEFT JOIN orders ON users.id = orders.user_id
    "
    );
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo “Name: “ . $row[‘name’] . “, Product: “ . ($row[‘product’] ?? ‘None’) . “<br>”;
    }
    ?>


    Right Join

    Retrieve all orders, including those without matching users:

    php
    <?php
    $stmt = $conn->query("
    SELECT users.name, orders.product, orders.amount
    FROM users
    RIGHT JOIN orders ON users.id = orders.user_id
    "
    );
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo “Name: “ . ($row[‘name’] ?? ‘Unknown’) . “, Product: “ . $row[‘product’] . “<br>”;
    }
    ?>


    15.4 Practical Example

    Task Management System

    1. Create a tasks table:
      sql
      CREATE TABLE tasks (
      id INT AUTO_INCREMENT PRIMARY KEY,
      user_id INT,
      description VARCHAR(255),
      status ENUM('pending', 'completed'),
      FOREIGN KEY (user_id) REFERENCES users(id)
      );
    2. Implement the following:
      • Prepared Statements:
        • Add a new task for a user.
        • Update the status of a task.
      • Transactions:
        • Deduct a task’s cost from a user’s balance only if the task is added successfully.
      • Joins:
        • Display all tasks with user details.

    Activities and Exercises

    1. Prepared Statements:
      • Write a script to securely insert and retrieve data from a products table.
    2. Transactions:
      • Simulate a banking system where users can transfer money between accounts.
    3. Joins:
      • Create a report showing users and their orders, including users with no orders.

    Assignment

    1. Create two tables: students and courses with a many-to-many relationship using a student_courses table.
    2. Implement the following:
      • Add a new course for a student using prepared statements.
      • Display all courses a student is enrolled in using joins.
      • Use transactions to ensure course enrollment is recorded correctly.

    Summary

    In this lesson, you learned:

    1. How to use prepared statements to prevent SQL injection and enhance security.
    2. How to manage complex database operations with transactions.
    3. How to retrieve related data using joins.

    These skills are critical for building secure and efficient database-driven applications. Let me know if you need further clarification or examples!

  • 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!