If you want to work in CodeIgniter 4 you need to download and install CodeIgniter 4 using Composer or download manually. Once installation is done you can create a project in CodeIgniter 4 and start working on it. In this topic, we will see how to install and create a project in CodeIgniter 4 and test for database connection using MySQL.
Composer Installation vs Manual Installation of CodeIgniter 4
CodeIgniter 4 can be installed using Composer or manually without Composer. Many people prefer Composer installation as it is easier to upgrade to a new version.
So, let us see how we can install and test CodeIgniter 4 in localhost.
Composer Installation
Installing CodeIgniter 4 using composer is very easy and also it is a preferred way to install CodeIgniter 4. If you do not have a composer you need to install it first. Composer is a tool that can manage the libraries you need to install/update for PHP. You can download Composer from https://getcomposer.org. It is quick and easy. Once composer is installed, go to the command prompt and type composer. If installed successfully, it will show the options and commands available for the composer as below.
Now, go to the desired folder where you want to install CodeIgniter 4 for the project. For us, we created a folder named "projects" in D: drive. We will run the below command from D:/projects
in the command prompt.
composer create-project codeigniter4/appstarter ci4-test
So, D:/projects/ci4-test
will be the root directory for the project. When installation is complete, a folder named ci4-test will be created under D:/projects
and CodeIgniter 4 will be installed with a skeleton application.
Manual Installation
If you do not want to install using Composer, you can download the latest version of CodeIgniter 4 and extract it to your project root folder. You can download CodeIgniter 4 from https://codeigniter.com/download. Select CodeIgniter 4 and download. It is a zip file; extract it to make it the project root folder.
Basic Configuration and Testing
Before we test it, let us do some basic setup or verify a few things. These setups are necessary irrespective of composer or manual installation.
- Make sure,
'intl'
and'mbstring'
extensions are installed. Please check the CodeIgniter user guide about server requirements. - Open
php.ini
(xampp/php/php.ini) in Notepad and find the lines withextension=curl, extension=intl, extension=mbstring
, all these lines should be uncommented to enable these extensions. - Open the file
App.php
from app/Config folder and update baseURL ashttp://localhost:8080/
and make index page as blank.public $baseURL = 'http://localhost:8080/'; // public $indexPage = '';
- We need to update the environment as development. Copy
env
file located in the project root to.env
. Open the.env
file and replace "production" with "development" in the line"# CI_ENVIRONMENT = production"
. Remove # from the beginning of the line. See below:# CI_ENVIRONMENT = production CI_ENVIRONMENT = development
Test using PHP Local Web Server
You can use the PHP built-in web server as the local Development Server and test your application. Go to the command prompt and type in the below command from your project root.
php spark serve
After you enter the above command, the local server will be started in port 8080.
Run http:// localhost:8080 in the browser and you should see the below screen. If you see this, your installation is complete.
Test For Database Connection in CoddeIgniter 4
We will Connect to the MySQL database in CodeIgniter 4 and display data in a view from a database table. Use the below scripts to create a table and insert data into the MySQL database.
product.sql
CREATE TABLE `product` (
`product_id` int(11) NOT NULL,
`product_name` varchar(200) NOT NULL,
`price` decimal(12,2) NOT NULL,
`stock` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `product` (`product_id`, `product_name`, `price`, `stock`) VALUES
(1, 'Sofa', '10000.00', 34),
(2, 'Dining Table', '6000.00', 100),
(3, 'Dining Chair(set of 4)', '5000.00', 30),
(4, 'Mattress', '8000.00', 111);
ALTER TABLE `product`
ADD PRIMARY KEY (`product_id`);
ALTER TABLE `product`
MODIFY `product_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
Update Database.php in app/Config for database name, userid and password.
Update $default as below:
public $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'demo',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => (ENVIRONMENT !== 'production'),
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
];
We will create a Controller, a Model and a View for our testing. Our Controller is Product.php
, Model is ModelProduct.php
and View is product.php
.
The controller calls a model method to get all products and then sends the data to the view. The view displays the data in an html table.
app/Controllers/Product.php
<?php
namespace App\Controllers;
use App\Models\ModelProduct;
class Product extends BaseController {
protected $model;
public function __construct() {
$this->model = new ModelProduct();
}
public function index() {
$data['product_data'] = $this->model->getProducts();
echo view('product',$data);
}
}
app/Models/ModelProduct.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class ModelProduct extends Model{
protected $db;
public function __construct() {
parent::__construct();
$this->db = db_connect();
}
function getProducts() {
$builder = $this->db->table('product');
$builder->orderBy('product_id');
$query = $builder->get();
return $query->getResult();
}
}
app/Views/product.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Display Products</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h2>List of Products</h2>
<div class="table-responsive">
<table class="table table-bordered table-hover">
<thead>
<tr><th>Product Id</th><th>Product Name</th><th>Price (INR)</th><th>Stock</th>
</tr>
</thead>
<?php if (!empty($product_data)) {
foreach ($product_data as $row) { ?>
<tr>
<td><?= esc($row->product_id) ?></td>
<td><?= esc($row->product_name) ?></td>
<td><?= esc($row->price) ?></td>
<td><?= esc($row->stock) ?></td>
</tr>
<?php }
}
else
echo '<td colspan = "5"> No Products Available</td><tr>'; ?>
</table>
</div>
</div>
</body>
</html>
Update default controller in app/Config/Routes.php
.
$routes->setDefaultController('Product');
Also change below line to include Product controller. $routes->get('/', 'Home::index');
To $routes->get('/', 'Product::index');
We are all set to test for database connection now. Start the PHP Local Server by running the command "php spark serve" as described before. Then, run http://localhost:8080/
in the browser. You should see the below screen displaying the products in an html table:
Conclusion
Installation and testing of CodeIgniter 4 are necessary every time you create a new application. These are the basic things that need to be done before you start writing code for your project. I hope it was a useful topic for you.
Post a Comment