Web Framework and Services — Study Notes

Unit 03

MVC Architecture, URL Routing, Database Connectivity, Sessions & Flashdata, File Management, Helpers & Libraries in CodeIgniter

9 Questions 5 Marks Each Web Framework and Services
01
5 Marks Question

Explain MVC Architecture in CodeIgniter

MVC stands for Model–View–Controller. It is a software design pattern used in CodeIgniter to divide an application into three separate components, with each component having a specific responsibility.

MVC separates business logic, presentation, and user requests, making the application easier to develop, understand, maintain, and modify.

MVC Architecture

User / Browser
                    |
                    | HTTP Request
                    ↓
              ┌─────────────┐
              │ Controller  │
              └─────────────┘
                /         \
               /           \
              ↓             ↓
       ┌─────────────┐  ┌─────────────┐
       │    Model    │  │    View     │
       └─────────────┘  └─────────────┘
              |               |
              ↓               ↓
          Database        Web Page/UI
01
Model

The Model represents the data structure of the application. It generally contains functions for retrieving, inserting, and updating data, and working with application data. Thus, the Model mainly handles data and database-related operations.

class StudentModel extends Model
{
    public function getStudents()
    {
        return $this->findAll();
    }
}
02
View

The View represents the information presented to the user. It is normally a web page containing HTML, but it can also be a page fragment such as a header or footer, or other types of pages. The View is mainly responsible for the presentation/user interface.

<h2>Student Details</h2>

<p>Name: Rahul</p>
<p>Course: BCA</p>
03
Controller

The Controller acts as an intermediary between the Model, View, and other resources required to process an HTTP request and generate a web page. It receives the user's request, communicates with the Model when data is required, and then sends the appropriate data to the View.

class Student extends BaseController
{
    public function index()
    {
        $model = new StudentModel();
        $data['students'] = $model->getStudents();

        return view('students', $data);
    }
}

Working of MVC

User Request → Controller → Model → Database

Model → Controller → View → Response to User

For example, when a user requests a student page:

Step 1: The Controller receives the request.

Step 2: The Controller asks the Model for student data.

Step 3: The Model retrieves the data from the database.

Step 4: The Model returns the data to the Controller.

Step 5: The Controller passes the data to the View.

Step 6: The View displays the student information to the user.

Advantages of MVC

Separation of concerns
Data, presentation, and request handling are separated.
Easy maintenance
Changes in one part have less effect on other parts.
Code reusability
Models and other components can be reused.
Easy development
Different parts of the application can be developed separately.
Better organization
Large applications become easier to understand and manage.
Conclusion CodeIgniter's MVC architecture divides an application into Model, View, and Controller. The Model handles data, the View handles presentation, and the Controller processes requests and coordinates between them. This separation makes CodeIgniter applications more organized, maintainable, and easier to modify.
02
5 Marks Question

Explain URL Routing in CodeIgniter

URL Routing is the process of connecting a URL requested by the user to a specific controller and its method in a CodeIgniter application.

URL → Route → Controller → Method → Response

For example, when the user visits http://localhost/myproject/course, CodeIgniter checks the defined routes and determines which controller method should execute: /course → Course Controller → index().

What is a Route?

A route defines which controller method should be executed when a particular URL is requested. In CodeIgniter 4, routes are generally defined in app/Config/Routes.php.

$routes->get('/course', 'Course::index');

This means /course is the URL, Course is the Controller, index is the Controller method, and get() represents an HTTP GET request.

Types of Routing in CodeIgniter 4

01
Defined Route Routing

In Defined Route Routing, the developer manually specifies the URL and the corresponding controller method.

$routes->get('/course', 'Course::index');

When /course is requested, CodeIgniter executes the index() method of the Course controller.

Advantages: provides more control over URLs; URLs can be customized; provides better security; only explicitly defined routes are available.

02
Auto Routing

In Auto Routing, CodeIgniter automatically determines the controller and method from the requested URL according to its routing conventions. There is no need to manually define every route.

/course/index
      ↓
Course::index()

Example of Routes.php

<?php

use CodeIgniter\Router\RouteCollection;

$routes->get('/', 'Home::index');
$routes->get('course', 'Course::index');
$routes->post('course/save', 'Course::save');
URL Controller Method Request
/Homeindex()GET
/courseCourseindex()GET
/course/saveCoursesave()POST

For example, $routes->post('course/save', 'Course::save'); means that when a form sends data to /course/save using POST, CodeIgniter executes the save() method of the Course controller.

Default Controller and Default Route

The default controller is the controller loaded when the user visits the application's base URL without specifying a controller. For example, http://localhost/myproject/ can execute Home::index().

The default route is normally defined in app/Config/Routes.php:

$routes->get('/', 'Home::index');

Here / represents the root URL, Home is the controller, and index is the method.

Conclusion URL routing in CodeIgniter provides a connection between user requests and application logic. It maps URLs to specific controller methods and can be implemented using Defined Routes or Auto Routing. Routes are generally configured in app/Config/Routes.php, making URL handling organized and controllable.
03
5 Marks Question

Explain MySQLi or PDO (Database Connection) in CodeIgniter

PHP provides two main extensions for connecting with MySQL databases: MySQLi (MySQL Improved) and PDO (PHP Data Objects). Both can be used to connect PHP applications with databases and support prepared statements, which help protect applications from SQL injection.

Note: In CodeIgniter, database operations are normally handled through its Model and database layer, rather than creating a raw MySQLi/PDO connection in every controller. The notes first explain MySQLi/PDO as PHP database connection methods and then show CodeIgniter Models using built-in database functions.
01
MySQLi

MySQLi stands for MySQL Improved. It is a PHP extension used to connect specifically with MySQL databases.

Features: works with MySQL databases; easy to use; supports Object-Oriented and Procedural programming styles; supports prepared statements; provides good performance for MySQL applications.

<?php

$host = "localhost";
$user = "root";
$password = "";
$database = "ComplaintDB";

$conn = new mysqli($host, $user, $password, $database);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

echo "Database connected successfully";
?>

Here, new mysqli() creates a connection between PHP and the MySQL database.

02
PDO

PDO stands for PHP Data Objects. It is a database access layer that allows PHP to connect with different types of databases using a similar programming style. PDO supports databases such as MySQL, PostgreSQL, SQLite, Oracle, and SQL Server.

<?php

$host = "localhost";
$db = "ComplaintDB";
$user = "root";
$password = "";

$conn = new PDO(
    "mysql:host=$host;dbname=$db",
    $user,
    $password
);

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

echo "Database connected successfully";
?>

MySQLi vs PDO

Feature MySQLi PDO
Database SupportOnly MySQLMultiple databases
Programming StyleObject-oriented and proceduralObject-oriented
Prepared StatementsSupportedSupported
PortabilityLess portableMore portable
Ease of UseEasy to learnSlightly advanced
Database SwitchingDifficultEasier

Database Connection in CodeIgniter

CodeIgniter provides a database layer so that the Model can connect to the database and perform operations such as findAll() (retrieve all records), find() (retrieve a record), insert() (insert data), update() (update data), and delete() (delete data). For example:

<?php

namespace App\Models;

use CodeIgniter\Model;

class CourseModel extends Model
{
    protected $table = 'course';
    protected $primaryKey = 'Id';
    protected $allowedFields = ['Id', 'Name'];
    protected $returnType = 'array';
}

The CodeIgniter Model provides these built-in database functions and works with the specified course table.

Working

Controller
     ↓
Model
     ↓
Database
     ↓
Model
     ↓
Controller
     ↓
View

For example, the Controller can create a CourseModel object and use:

$model = new CourseModel();
$data['courses'] = $model->findAll();

return view('course_form', $data);

Here, findAll() retrieves the course records from the database and the Controller sends them to the View.

Conclusion MySQLi and PDO are PHP methods for database connectivity. MySQLi is specifically designed for MySQL, while PDO supports multiple databases and is more portable. In CodeIgniter, database interaction is organized through the Model, which provides built-in methods for performing CRUD operations on the database.
04
5 Marks Question

How to Use/Manage Session and Flash Data in CodeIgniter?

Session in CodeIgniter is used to store user data across multiple requests. It can be used for information such as user ID, username, and login status.

Flashdata is a special type of session data that is stored temporarily and is automatically removed after it is used. It is commonly used for success and error messages.

01
Session Management

Setting Session Data — session data can be stored using:

session()->set([
    'username' => 'Rahul',
    'user_id' => 101
]);

Getting Session Data — to retrieve stored session data:

$username = session()->get('username');

Removing Session Data — a particular session value can be removed using:

session()->remove('username');
02
Flashdata

Flashdata is used when information is required only temporarily, generally for the next request — for example, displaying "Registration successful." after a successful registration.

Setting Flashdata:

session()->setFlashdata(
    'message',
    'Registration successful!'
);

Retrieving Flashdata:

$message = session()->getFlashdata('message');

After it has been used, the flashdata automatically expires.

Difference Between Session and Flashdata

Feature Session Flashdata
PurposeStores data for multiple requestsStores temporary data
LifetimeRemains until manually removed or session endsAutomatically removed after use
ExamplesUser ID, username, login statusSuccess/error messages
Set Methodsession()->set()session()->setFlashdata()
Get Methodsession()->get()session()->getFlashdata()
Removalsession()->remove()Automatically expires

Example

// Store user information
session()->set('username', 'Rahul');

// Retrieve user information
$username = session()->get('username');

// Store temporary success message
session()->setFlashdata(
    'message',
    'Data saved successfully!'
);

// Retrieve temporary message
$message = session()->getFlashdata('message');
Conclusion CodeIgniter provides session management for maintaining user-related information across requests. Normal session data is used for persistent information such as login status, while Flashdata is used for temporary messages such as success or error notifications.
05
5 Marks Question

Explain File Management in CodeIgniter with Examples

File management in CodeIgniter refers to handling files uploaded by users, such as images, documents, and other files. CodeIgniter provides the $this->request object and an UploadedFile object to obtain and manage uploaded files.

A common approach is to create an upload folder inside the project's public directory, for example public/Uploads/.

Steps for File Upload

01
Create Upload Folder

Create the following folder in the CodeIgniter project:

public/Uploads/

Example:
C:\xampp\htdocs\codeigniter4-framework\public\Uploads
02
Get the Uploaded File

The uploaded file can be obtained using:

$file = $this->request->getFile('myfile');

Here, myfile is the name of the file input in the HTML form.

03
Check Whether the File is Valid
if ($file->isValid()) {
    // File is valid
}

The isValid() method checks whether the uploaded file is valid.

04
Generate a File Name

CodeIgniter can generate a random file name using:

$newName = $file->getRandomName();

This is useful to avoid conflicts between files having the same name.

05
Move the File

The file can then be moved to the upload directory:

$file->move('public/Uploads', $newName);

The move() method moves the uploaded file to the specified destination.

Complete Example

HTML Form

<form action="/upload" method="post" enctype="multipart/form-data">

    <input type="file" name="myfile">

    <button type="submit">Upload</button>

</form>

Controller

public function upload()
{
    $file = $this->request->getFile('myfile');

    if ($file->isValid()) {

        $newName = $file->getRandomName();

        $file->move('public/Uploads', $newName);

        return "File uploaded successfully";
    }

    return "File upload failed";
}

Important File Management Methods

Method Purpose
$this->request->getFile('myfile')Gets the uploaded file
$file->isValid()Checks whether the upload is valid
$file->hasMoved()Checks whether the file has already been moved
$file->getName()Gets the file name
$file->getRandomName()Generates a random file name
$file->getClientName()Gets the original client file name
$file->getClientExtension()Gets the file extension
$file->getSize()Gets the file size
$file->move()Moves the file to the destination
Conclusion CodeIgniter provides convenient methods for uploading and managing files. The uploaded file is obtained using getFile(), checked using isValid(), optionally given a random name using getRandomName(), and finally stored using move(). This makes file-upload handling simple and organized in CodeIgniter applications.
06
5 Marks Question

Explain the Use of Helpers and Libraries in CodeIgniter

CodeIgniter provides Helpers and Libraries to simplify common web-development tasks. They provide reusable functionality so that developers do not have to write the same code repeatedly.

01
Helpers

A Helper is a collection of simple functions designed to perform tasks of a particular category. Helpers are procedural functions, not classes or objects. Each helper function generally performs a specific task.

Common helpers: URL Helper — helps in creating URLs and links; Form Helper — helps in creating form elements; Text Helper — provides text formatting functions; Cookie Helper — helps set and read cookies; Filesystem Helper — provides functions for working with files.

A helper can be loaded using:

helper('url');

After loading the URL Helper, its functions can be used for URL-related operations.

02
Libraries / Services

A Library generally provides a class or service containing more complex functionality than a helper. In CodeIgniter 4, many libraries are accessed using the service() function.

Example: Validation Library

$validation = \Config\Services::validation();

$validation->setRules([
    'name'  => 'required',
    'email' => 'required|valid_email'
]);

Here, the validation service provides functionality for checking whether form data satisfies the specified rules.

Difference Between Helpers and Libraries

Feature Helpers Libraries
StructureCollection of functionsClass/service
Programming styleProceduralObject-oriented
ComplexityUsed for simple tasksUsed for more complex functionality
ExampleURL Helper, Form HelperValidation Library
Loadinghelper('url')service() / CodeIgniter service

Advantages

Code reusability
Common functionality can be reused.
Less coding
Developers don't need to implement common tasks from scratch.
Faster development
Ready-made functionality speeds up development.
Better organization
Related functionality is grouped together.
Simplifies complex tasks
Libraries provide ready-made classes/services for advanced operations.
Conclusion Helpers and Libraries are reusable features provided by CodeIgniter. Helpers provide simple procedural functions for tasks such as URLs, forms, cookies, and files, while Libraries/Services provide more complex class-based functionality such as validation.
07
5 Marks Question

Explain the Steps to Connect PHP with Database

PHP can connect to a database using database extensions such as MySQLi or PDO. The notes specifically cover both methods. MySQLi is designed for MySQL databases, while PDO can work with multiple database systems. Both support Prepared Statements, which help protect against SQL injection.

Steps to Connect PHP with a Database

01
Create the Database

First, create the required database in MySQL.

CREATE DATABASE CollegeDB;

Then select it:

USE CollegeDB;
02
Choose a Database Extension

PHP mainly provides two extensions for database connectivity:

  • MySQLi (MySQL Improved) – works with MySQL.
  • PDO (PHP Data Objects) – provides a common interface for different databases such as MySQL, PostgreSQL, SQLite, Oracle and SQL Server.
03
Provide Database Connection Details

The connection requires details such as Server/host name, Username, Password, and Database name.

For example, using MySQLi:

<?php

$host = "localhost";
$username = "root";
$password = "";
$database = "CollegeDB";

$conn = new mysqli($host, $username, $password, $database);

?>

Here, the mysqli connection object is created using the database credentials.

04
Check the Connection

The connection should be checked to make sure that PHP was able to connect to the database.

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

echo "Database connected successfully";
05
Execute SQL Queries

After establishing the connection, PHP can execute SQL queries to retrieve, insert, update or delete database records.

For example:

$sql = "SELECT * FROM students";
$result = $conn->query($sql);

while ($row = $result->fetch_assoc()) {
    echo $row["name"] . "<br>";
}

For user-provided data, Prepared Statements should be used instead of directly inserting user input into SQL queries. The notes specifically state that Prepared Statements protect against SQL Injection.

06
Close the Connection

After completing the required database operations, the connection can be closed:

$conn->close();

This releases the database connection.

Complete Example

<?php

$host = "localhost";
$username = "root";
$password = "";
$database = "CollegeDB";

// Create connection
$conn = new mysqli($host, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Execute query
$sql = "SELECT * FROM students";
$result = $conn->query($sql);

// Display data
while ($row = $result->fetch_assoc()) {
    echo $row["name"] . "<br>";
}

// Close connection
$conn->close();

?>
Steps in Short Create Database → Choose MySQLi/PDO → Provide Credentials → Create Connection → Check Connection → Execute Query → Fetch/Process Data → Close Connection
08
5 Marks Question

Short Note on AJAX Requests to PHP

AJAX (Asynchronous JavaScript and XML) allows a web page to communicate with a PHP server in the background without reloading the entire page. JavaScript sends a request to PHP, PHP processes the request and sends a response, and JavaScript displays the result on the current page. This makes web applications faster and more interactive.

Steps of an AJAX Request to PHP

01
User provides input

For example, the user types a complaint or search text into a textbox.

02
JavaScript function is triggered

An event such as onkeyup can automatically call a JavaScript function whenever the user types.

<input type="text" id="search" onkeyup="searchComplaint()">
03
Create an AJAX object

JavaScript creates an XMLHttpRequest object.

var xhttp = new XMLHttpRequest();

This object sends the HTTP request to the PHP server without refreshing the page.

04
Send request to PHP
xhttp.open(
    "GET",
    "searchAjax.php?search=" + str,
    true
);
xhttp.send();

Here, searchAjax.php is the PHP file that receives and processes the request.

05
PHP processes the request

PHP receives the search value, performs the required operation such as searching the database, and returns the result.

06
Display the response without page reload
document.getElementById("result").innerHTML =
    this.responseText;

The response from PHP is inserted directly into the required HTML element.

Example

In a live complaint search system, the user types a search term. The onkeyup event calls JavaScript, which sends the search text to PHP using XMLHttpRequest. PHP searches the database and returns matching complaints. The results are then displayed immediately on the same page.

Advantages of AJAX with PHP

No complete page reload
Only the required data is transferred and refreshed.
Asynchronous communication
Provides asynchronous communication.
Uses less bandwidth
Uses less bandwidth.
Faster & interactive
Makes applications faster and more interactive compared with traditional form submission.
09
5 Marks Question

Explain How JSON is Generated and Parsed in PHP with json_encode() and json_decode()

JSON (JavaScript Object Notation) is a lightweight format used for exchanging data between JavaScript and PHP. In PHP, two important functions are used for handling JSON:

  • json_encode() – converts PHP arrays or objects into JSON format.
  • json_decode() – converts a JSON string into a PHP object or associative array.
01
Generating JSON using json_encode()

When PHP needs to send data to a browser or JavaScript application, it can convert a PHP array or object into JSON using json_encode().

Example:

<?php

$student = [
    "name" => "Rahul",
    "age" => 20,
    "course" => "BCA"
];

$jsonData = json_encode($student);

echo $jsonData;

?>

Output:

{"name":"Rahul","age":20,"course":"BCA"}

Here, the PHP associative array is converted into a JSON string using json_encode().

02
Parsing JSON using json_decode()

When PHP receives JSON data from JavaScript or another client, it can convert the JSON string back into a PHP object or associative array using json_decode(). This allows PHP to access and manipulate the received data.

Example:

<?php

$jsonData = '{"name":"Rahul","age":20,"course":"BCA"}';

$student = json_decode($jsonData, true);

echo $student["name"];
echo $student["age"];

?>

Output:

Rahul
20

The second argument true makes json_decode() return an associative array. Without it, the JSON is normally decoded into a PHP object.

03
JSON Data Exchange between JavaScript and PHP

The overall process can be represented as:

JavaScript
    |
    | JSON Request
    ↓
   PHP
    |
    | json_decode()
    ↓
PHP Array/Object
    |
    | Process data / Database operation
    ↓
PHP Array/Object
    |
    | json_encode()
    ↓
   JSON Response
    |
    ↓
JavaScript

PHP can receive requests from JavaScript, interact with databases such as MySQL, and after processing the data, convert the resulting PHP array/object into JSON using json_encode() and send it back to the browser.

Conclusion Thus, json_encode() is used to generate JSON from PHP data, while json_decode() is used to parse JSON into PHP data. These functions make communication and data exchange between JavaScript and PHP simple and reliable.