Typeahead CodeIgniter 4 Database AutoComplete Search

Reading Time: 5 minutes
5,078 Views

Inside this article we will see the concept of autocomplete search using typeahead jquery plugin in CodeIgniter 4. This autocomplete search will be total dynamic which searches data from database.

You will get the complete concept of CodeIgniter 4 database autocomplete search using typeahead.

Learn More –

This tutorial will use a complete basic idea to learn as well as to integrate in a very easy way. This will use typeahead jquery plugin which binds autocomplete data set.

Let’s get started.


CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Environment (.env) Setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

Open project in terminal

cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.


Create Database

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

We will use MySQL command to create database. Run this command into Sql tab of PhpMyAdmin.

CREATE DATABASE codeigniter4_app;

Successfully, we have created a database.


Create Database Table

Next, we need a table. That table will be responsible to store data.

CREATE TABLE `countries` (
 `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
 `iso` char(2) COLLATE utf8mb4_unicode_ci NOT NULL,
 `name` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
 `nicename` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
 `iso3` char(3) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 `numcode` smallint(6) DEFAULT NULL,
 `phonecode` int(11) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Successfully, we have created a table.


Database Connection

Open .env file from project root.

Search for DATABASE. You should see the connection environment variables into it. Put your updated details of database connection string values.

 
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

database.default.hostname = localhost
database.default.database = codeigniter4_app
database.default.username = admin
database.default.password = admin
database.default.DBDriver = MySQLi
database.default.DBPrefix =
database.default.port = 3306
  

Now, database successfully connected with the application.


Insert Data into Table

As we have created a table named as countries. We need some data into this table to test autocomplete search.

For data here we have the link of github.

Run the given mysql query to your database.

When you will run, you will get data something like this.


Create Controller

Back to terminal and run this command to create controller file.

$ php spark make:controller Search --suffix

It will create SearchController.php file inside /app/Controllers folder.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class SearchController extends BaseController
{
	public function __construct()
	{
		$this->db = db_connect();
	}

	public function index()
	{
		return view("search");
	}

	public function autocomplete()
	{
		$query = $this->request->getVar("query");

		$builder = $this->db->table("countries");

		$builder->select('*');
		$builder->like('nicename', $query, 'both');
		$query = $builder->get();
		$data = $query->getResult();

		//echo $this->db->getLastQuery();
		$countries = [];
		
		if (count($data) > 0) {

			foreach ($data as $country) {
				$countries[] = $country->nicename;
			}
		}
		return json_encode($countries);
	}
}

Add Routes

Open Routes.php file from /app/Config folder. Add these given routes into it.

//..

$routes->get("search", "SearchController::index", ["as" => "search"]);
$routes->get("autocomplete", "SearchController::autocomplete", ["as" => "autocomplete"]);

//..

Create Layout File

Create search.php file inside /app/Views folder.

Open search.php and write this complete code into it.

<!DOCTYPE html>
<html>

<head>
    <title>Autocomplete Search From Database CodeIgniter 4</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js">
    </script>
</head>

<body>

    <div class="container" style="margin-top: 40px;">
        <div class="panel panel-primary">
            <div class="panel-heading">CodeIgniter 4 Autocomplete Search</div>
            <div class="panel-body">
                <label>Search here...</label>
                <input class="typeahead form-control" type="text">
            </div>
        </div>
    </div>

    <script type="text/javascript">
        var path = "<?= base_url('autocomplete') ?>";
        $('input.typeahead').typeahead({
            source: function(query, process) {
                return $.get(path, {
                    query: query
                }, function(data) {
                    var data = $.parseJSON(data);
                    return process(data);
                });
            }
        });

    </script>

</body>

</html>

Application Testing

Open project terminal and start development server via command:

php spark serve

URL – http://localhost:8080/search

We hope this article helped you to learn about CodeIgniter 4 database autocomplete search using typeahead in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.