Know how to Implement Rating/Review System in CodeIgniter

by Shailender K. 4 minute read 36 views

Implement a dynamic rating and review system in CodeIgniter with Bootstrap and jQuery to boost trust, user engagement, and conversions for scalable web applications.

Key Points

  • 93% of users read reviews before making a purchase decision.
  • Customer reviews can increase conversions by 270% for higher-priced products.
  • Displaying reviews boosts product trust for 72% of customers.

In today’s digital ecosystem, user feedback has become a key driver of trust, engagement, and conversion across all types of platforms. Whether you're developing an eCommerce store, a SaaS dashboard, or a services marketplace, a robust rating and review system enhances transparency and helps other users make informed decisions. For developers building with CodeIgniter, integrating such a feature is both scalable and straightforward.

This guide demonstrates how to implement a star-based rating and review system in CodeIgniter, using Bootstrap for UI and jQuery for dynamic star interaction. It includes the model-view-controller architecture, database interaction, and real-time star updates, ideal for developers involved in scalable custom app development.

Step 1: Define Routes

Routes in CodeIgniter connect URL endpoints to controller methods. They serve as a bridge between user actions (like clicking a button) and the appropriate backend logic. By defining the following routes, we allow users to submit and view product reviews:

Start by defining your application routes inside app/Config/Routes.php:

                                        use CodeIgniter\Router\RouteCollection;

$routes->post('save-review', 'ReviewController::save_review');
$routes->get('product-details/(:any)', 'ReviewController::product_details/$1');
                                    

  • save-review: Submits review and rating to the database

  • product-details/{id}: Displays product info along with its reviews

Whether you're building with Laravel or CodeIgniter, defining clean and RESTful routes is a best practice for Backend Developers.

Step 2: Create Database Table

A database table holds structured data. In this case, the reviews table stores the relationship between products, users and their submitted ratings/reviews.

                                        CREATE TABLE reviews (
    id INT AUTO_INCREMENT PRIMARY KEY,
    product_id INT NOT NULL,
    user_id INT NOT NULL,
    rating INT NOT NULL CHECK (rating BETWEEN 1 AND 5),
    review TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
                                    

Well-designed database architecture is crucial for scalable custom web development and managing large volumes of user-generated content.

Step 3: Create the Review Model

The model in MVC handles all database interactions. It abstracts complex SQL queries into reusable functions and ensures data integrity.

Create the file app/Models/ReviewModel.php with the following code:

                                        namespace App\Models;

use CodeIgniter\Model;

class ReviewModel extends Model
{
    protected $table            = 'reviews';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;

    protected $allowedFields    = [
        'user_id',
        'rating',
        'review',
        'product_id',
    ];

    protected $DBGroup          = 'customDB';
    protected $useTimestamps    = true;
    protected $createdField     = 'created_at';

    public function add_review($data)
    {
        return $this->insert($data);
    }

    public function get_reviews($product_id)
    {
        return $this->select('reviews.*, users.name, users.image')
                    ->join('users', 'users.id = reviews.user_id')
                    ->where('reviews.product_id', $product_id)
                    ->orderBy('reviews.created_at', 'DESC')
                    ->findAll();
    }

    public function get_average_rating($product_id)
    {
        $result = $this->selectAvg('rating')
                       ->where('product_id', $product_id)
                       ->first();

        return $result['rating'] ?? 0;
    }
}
                                    

This layer is essential for Backend Developers aiming to build secure, reusable data logic across modern web platforms.

Step 4: Create the Review Controller

Controllers are responsible for processing user inputs, interacting with models, and rendering views. They define the business logic for an application.

Create the file app/Controllers/ReviewController.php with the following content:

                                        namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\ReviewModel;
use CodeIgniter\Database\BaseConnection;

class ReviewController extends BaseController
{
    protected $session;
    protected $reviewModel;
    protected $db;

    public function __construct()
    {
        $this->session = \Config\Services::session();
        $this->reviewModel = new ReviewModel();
        $this->db = \Config\Database::connect('customDB');
    }

    public function save_review()
    {
        $product_id = $this->request->getPost('product_id');
        $data = [
            'product_id' => $product_id,
            'user_id' => $this->session->get('user_id'),
            'rating' => $this->request->getPost('rating'),
            'review' => $this->request->getPost('review'),
        ];

        $result = $this->reviewModel->add_review($data);

        if ($result) {
            $this->session->setFlashdata('success', 'Review added successfully!');
        } else {
            $this->session->setFlashdata('error', 'Failed to add review.');
        }

        return redirect()->to('product-details/' . $product_id);
    }

    public function product_details($product_id)
    {
        $data['product'] = $this->db->table('products')
                                    ->where('product_id', $product_id)
                                    ->get()
                                    ->getRow();

        $data['reviews'] = $this->reviewModel->get_reviews($product_id);
        $data['average_rating'] = $this->reviewModel->get_average_rating($product_id);

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

Efficient controller design is fundamental for scalable website development services, particularly when working with teams of Front-end Developers and Backend Developers.

Step 5: Create the View – reviews_view.php

Views are user-facing templates that render dynamic content using HTML, CSS, and JS. They display forms, product details, and user reviews in a readable and interactive layout.

This file handles both the product details and the rating form modal. Create it in the app/Views/ directory.

                                        <!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Rating & Review</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.6/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="pt-3">
    <div class="row">
        <div class="col-md-3 text-center">
            <img src="<?= base_url($product->image); ?>" alt="<?= ucfirst($product->name); ?>" class="img-thumbnail">
        </div>

        <div class="col-md-5">
            <h4><?= $product->name; ?></h4>
            <p><?= $product->about; ?></p>
        </div>

        <div class="col-md-4">
            <div class="card p-3">
                <a href="#" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#exampleModalAddRating">
                    <i class="bi bi-star"></i> Write A Review
                </a>
            </div>
        </div>
    </div>
</div>

<!-- Rating Modal -->
<div class="modal fade" id="exampleModalAddRating" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="<?= base_url('save-review'); ?>" method="POST">
                <div class="modal-header">
                    <h5 class="modal-title">Rate & Review This Product</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="product_id" value="<?= $product->product_id; ?>">
                    <div class="add_rating" data-rating="0">
                        <i class="bi bi-star"></i>
                        <i class="bi bi-star"></i>
                        <i class="bi bi-star"></i>
                        <i class="bi bi-star"></i>
                        <i class="bi bi-star"></i>
                    </div>
                    <input type="hidden" id="hidden_rating" name="rating" value="0">
                    <div class="form-group mt-3">
                        <label for="review">Your Review</label>
                        <textarea name="review" class="form-control" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Submit Review</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Display Reviews -->
<div class="mt-4">
    <h3>User Reviews</h3>
    <p>Average Rating: <strong><?= round($average_rating, 2); ?>/5</strong></p>

    <?php if (count($reviews) > 0): ?>
        <?php foreach ($reviews as $review): ?>
            <div class="border p-3 mb-2">
                <strong><?= $review['name']; ?></strong> rated <?= $review['rating']; ?>/5
                <p><?= $review['review']; ?></p>
                <small><?= $review['created_at']; ?></small>
            </div>
        <?php endforeach; ?>
    <?php else: ?>
        <p>No reviews yet. Be the first to write one!</p>
    <?php endif; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.6/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $('.add_rating i.bi-star').on('click', function () {
            let rating = $(this).index() + 1;
            $('#hidden_rating').val(rating);
            $(this).siblings().addBack().each(function (index) {
                $(this).toggleClass('bi-star-fill', index < rating).toggleClass('bi-star', index >= rating);
            });
        });
    });
</script>
</body>
</html>
                                    

This is where Front-end Developers ensure the UI is intuitive, responsive and visually appealing using Bootstrap 5.3.

Final Tips & Best Practices

  • Security: Validate user inputs before saving reviews to prevent XSS or SQL injection.

  • Session Check: Ensure the user is authenticated before submitting a review.

  • User Experience: Consider AJAX submission for reviews to make the experience more seamless.

  • Performance: Cache average ratings if your product catalog is large.

  • Extensibility: You can expand this system to support likes/dislikes, review filtering, or reporting abuse.

Final Words

By following this guide, you’ve built a complete, scalable rating and review system suitable for any product-based web application. It’s highly adaptable and perfect for projects involving custom web development, eCommerce platforms, or review-based portals.

This implementation is not only simple but also extensible, making it a great fit for developers involved in custom app development and scalable web projects.

Tech Stack & Version

Frontend

  • Bootstrap
  • jQuery
  • HTML

 Backend

  • CodeIgniter
  • PHP
  • MVC

Deployment

  • cPanel
  • Heroku
  • VPS
img

©2025Digittrix Infotech Private Limited , All rights reserved.