CodeIgniter 4 CRUD example with Bootstrap and MySQL for Beginners

CodeIgniter 4 CRUD example with Bootstrap and MySQL for Beginners

CodeIgniter 4 released on 24 February 2020, with lots of features and functionalities. Let’s check the core benefits of Codeingiter 4

  • CodeIgniter has rich set of libraries
  • Efficient autoload process
  • performance is higher as it uses PHP 7.3+ version
  • CodeIgniter 4 has native support for .env files, allowing an optimization of the settings of the different environments.

Before we move ahead, We must need to follow basic and essential requirements to run and setup CodeIgniter 4. Prior Server Requirements for CodeIgniter 4 project on my blog.

  • Composer
  • Git bash
  • MySQL
  • PHP 7.3+
  • Xampp
  • Visual Studio Code
  • Enable intl extension. How?
  • Bootstrap v4

Create CodeIgniter 4 Project using Composer

composer create-project codeigniter4/appstarter cidemo

Start Server

php spark serve

Required Files

  • Model file
  • Controller file
  • View file
  • Routes.php (To define path)
  • Database.php for database connection cidemo\App\Config\Database.php(You need to change the database name)

Create Database:

create database using mysql. For this example I have used table name as contacts. Please check the table structure as below : NOTE: you can omit created_at and updated_at filed name.

Model file:

Path: C:\xampp\htdocs\cidemo\app\Models\Contact.php

<?php

namespace App\Models;
use CodeIgniter\Model;

class Contact extends Model
{
    protected $table= 'contacts';
    protected $allowedFields =[
		'firstname',
		'lastname',
		'email',
		'city',
		'country',
		'projecttitle',
		'requirements',
	];

	public function getRow($id){
		return $this->where('id', $id)->first();
	}

}

Controller File:

You can find methods like:

  • index() – To render main page
  • show() – To display all records,
  • edit() – To edit record- it will redirect on click of edit button from view file to edit form
  • update()- To update/change the data
  • delete() – to delete specific data

NOTE: (1) You need to include model here use App\Models\Contact; (2) path for Controller: C:\xampp\htdocs\cidemo\app\Controllers\ContactController.php

<?php
    namespace App\Controllers;
    use App\Models\Contact;
    use CodeIgniter\Controller;

    class ContactController extends BaseController{
        
        public function index()
        {
            echo view('contacts/createcontact');

        }
        public function create()
        {
            echo view('contacts/createcontact');
           $model = new Contact();
			$model->save([
                'firstname' => $this->request->getVar('firstname'),
                'lastname' => $this->request->getVar('lastname'),
                'email' => $this->request->getVar('email'),
                'city' => $this->request->getVar('city'),
                'country' => $this->request->getVar('country'),
                'projecttitle' => $this->request->getVar('projecttitle'),
                'requirements' => $this->request->getVar('requirements'),

           ]);
           return redirect()->route('contact');          
        }
        public function show(){
            $model = new Contact();
            $data = [
                'table' => $model->paginate(6),
                'pager' => $model->pager
            ];
            echo view('contacts/contactlist', $data);
        }
        public function delete($id){
            $model = new Contact();
            $model->delete($id);
            return redirect()->route('contacts/contactlist');
        }

        public function edit($id){
            
           
            $model = new Contact();
            $contact = $model->getRow($id);
            $data['table'] = $contact;
            echo view('contacts/edit',$data);           

        }

        public function update(){
            $model = new Contact();
            $id = $this->request->getVar('id');

            $data = [
                'firstname' => $this->request->getVar('firstname'),
                'lastname' => $this->request->getVar('lastname'),
                'email' => $this->request->getVar('email'),
                'city' => $this->request->getVar('city'),
                'country' => $this->request->getVar('country'),
                'projecttitle' => $this->request->getVar('projecttitle'),
                'requirements' => $this->request->getVar('requirements'),

           ];

           $model->update($id,$data);
           return $this->response->redirect(site_url('/contacts/contactlist'));
        }
    }

?>

View files:

(1) Create Form to insert data

File path: C:\xampp\htdocs\cidemo\app\Views\contacts\createcontact.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
         <!-- Bootstrap core CSS -->
            <link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/css/bootstrap.css');?>">
            <link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/css/style.css');?>">
    </head>
    <body>
        <div class="container-fluid bg-purple">
            <div class="container pb-2 pt-2"> 
                <div class=" text-center text-white h4">
                    Simple CodeIgniter-4 CRUD Application
                </div>
            </div>
        </div>
        <div class="container mt-5">
            <div class="row">
                <div class="col-md-12 ">
                    <a href="<?php echo base_url('/contacts/contactlist') ?>" class="btn btn-primary float-end">View Contact List</a>
                </div>
            </div>
        </div>
        <div class="container mt-5">
            <div class="row">
                <div class="col-md-12">
                  <?= \Config\Services::validation()->listErrors() ?>
                 
                            <form method="post" action="/contacts/createcontact">
                            <?= csrf_field() ?>
                            
                                <div class="row mb-4">                                    
                                    <div class="col">
                                        <div class="form-outline">
                                            <input type="text" id="firstname" name="firstname" class="form-control"/>
                                            <label class="form-label" for="firstname">First name</label>
                                        </div>
                                    </div>
                                    <div class="col">
                                        <div class="form-outline">
                                            <input type="text" id="lastname" name="lastname" class="form-control" />
                                            <label class="form-label" for="lastname">Last name</label>
                                        </div>
                                    </div>
                                </div>
                                    <div class="form-outline mb-4">
                                        <input type="text" id="email" name="email" class="form-control" />
                                        <label class="form-label" for="email">Email</label>
                                    </div>

                                    <!-- Text input -->
                                    <div class="form-outline mb-4">
                                        <input type="text" id="city" name="city" class="form-control" />
                                        <label class="form-label" for="city">City</label>
                                    </div>

                                    <!-- Email input -->
                                    <div class="form-outline mb-4">
                                        <input type="text" id="country" name="country" class="form-control" />
                                        <label class="form-label" for="country">Country</label>
                                    </div>

                                    <!-- Number input -->
                                    <div class="form-outline mb-4">
                                        <input type="text" id="projecttitle" name="projecttitle" class="form-control" />
                                        <label class="form-label" for="projecttitle">Project Title</label>
                                    </div>

                                    <!-- Message input -->
                                    <div class="form-outline mb-4">
                                        <input type="text" class="form-control" id="requirements" name="requirements" rows="4"/>
                                        <label class="form-label" for="requirements">Project Requirements</label>
                                    </div>

                                <!-- Submit button -->
                                <button type="submit" class="btn btn-primary btn-block mb-4">Submit your requirements</button>    
                                
                            </form>  
                       
                  
                </div>
            </div>
        </div>
         
     
    </body>
</html>

(2) Form to update records with prefilled data:

File path: C:\xampp\htdocs\cidemo\app\Views\contacts\edit.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
         <!-- Bootstrap core CSS -->
            <link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/css/bootstrap.css');?>">
            <link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/css/style.css');?>">
    </head>
    <body>
        <div class="container-fluid bg-purple">
            <div class="container pb-2 pt-2"> 
                <div class=" text-center text-white h4">
                    Simple CodeIgniter-4 CRUD Application
                </div>
            </div>
        </div>
        <div class="container mt-5">
            <div class="row">
                <div class="col-md-12 ">
                    <a href="<?php echo base_url('/contacts/contactlist') ?>" class="btn btn-primary float-end">View Contact List</a>
                </div>
            </div>
        </div>
        <div class="container mt-5">
            <div class="row">
                <div class="col-md-12">
                  <?= \Config\Services::validation()->listErrors() ?>
                 
                            <form method="post" action="/contacts/update">
                            <?= csrf_field() ?>
                            
                                <div class="row mb-4">    
                                    <input type="hidden" name="id" value="<?php echo $table['id'];?>">
                                    <div class="col">
                                        <div class="form-outline">
                                            <input type="text" id="firstname" name="firstname" value="<?php echo $table['firstname'];?>" class="form-control"/>
                                            <label class="form-label" for="firstname">First name</label>
                                        </div>
                                    </div>
                                    <div class="col">
                                        <div class="form-outline">
                                            <input type="text" id="lastname" name="lastname" value="<?php echo $table['lastname'];?>" class="form-control" />
                                            <label class="form-label" for="lastname">Last name</label>
                                        </div>
                                    </div>
                                </div>
                                    <div class="form-outline mb-4">
                                        <input type="text" id="email" name="email" value="<?php echo $table['email'];?>" class="form-control" />
                                        <label class="form-label" for="email">Email</label>
                                    </div>

                                    <!-- Text input -->
                                    <div class="form-outline mb-4">
                                        <input type="text" id="city" name="city" value="<?php echo $table['city'];?>" class="form-control" />
                                        <label class="form-label" for="city">City</label>
                                    </div>

                                    <!-- Email input -->
                                    <div class="form-outline mb-4">
                                        <input type="text" id="country" name="country" value="<?php echo $table['country'];?>" class="form-control" />
                                        <label class="form-label" for="country">Country</label>
                                    </div>

                                    <!-- Number input -->
                                    <div class="form-outline mb-4">
                                        <input type="text" id="projecttitle" name="projecttitle" value="<?php echo $table['projecttitle'];?>" class="form-control" />
                                        <label class="form-label" for="projecttitle">Project Title</label>
                                    </div>

                                    <!-- Message input -->
                                    <div class="form-outline mb-4">
                                        <input type="text" class="form-control" id="requirements" name="requirements" value="<?php echo $table['requirements'];?>" rows="4"/>
                                        <label class="form-label" for="requirements">Project Requirements</label>
                                    </div>

                                <!-- Submit button -->
                                <button type="submit" class="btn btn-primary btn-block mb-4">Update your requirements</button>    
                               
                            </form>  
                       
                  
                </div>
            </div>
        </div>
         
     
    </body>
</html>

(3) Display list of contacts:

File path: C:\xampp\htdocs\cidemo\app\Views\contacts\contactlist.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
         <!-- Bootstrap core CSS -->
            <link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/css/bootstrap.css');?>">
            <link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/css/style.css');?>">
    </head>
    <body>
        <div class="container-fluid bg-purple">
            <div class="container pb-2 pt-2"> 
                <div class=" text-center text-white h4">
                    Simple CodeIgniter-4 CRUD Application
                </div>
            </div>
        </div>
        <div class="container mt-5">
            <div class="row">
                <div class="col-md-12 ">
                    <a href="<?php echo base_url('contacts/createcontact'); ?>" class="btn btn-primary float-end">Add New Contact Details</a>
                </div>
            </div>
        </div>
        <div class="container mt-5">
            <div class="row">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-body ps-0 pe-0">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>First Name</th>
                                        <th>Last Name</th>
                                        <th>Email</th>
                                        <th>City</th>
                                        <th>Country</th>
                                        <th>Project Title</th>
                                        <th>Project Description</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($table as $t) {?>
                                               <tr>
                                               <td><?php echo $t['id'];?></td>
                                               <td><?php echo $t['firstname'];?></td>
                                               <td><?php echo $t['lastname'];?></td>
                                               <td><?php echo $t['email'];?></td>
                                               <td><?php echo $t['city'];?></td>
                                               <td><?php echo $t['country'];?></td>
                                               <td><?php echo $t['projecttitle'];?></td>
                                               <td><?php echo $t['requirements'];?></td>
                                               <td>
                                                   <a class="btn btn-primary btn-sm" href="<?php echo base_url('contacts/edit/'. $t['id']);?>">Edit</a>
                                                   <a class="btn btn-danger btn-sm" href="<?php echo base_url('contacts/delete/'. $t['id']);?>">Delete</a>
                                               </td>
                                           </tr>
                                 <?php   }?>
                             
                                </tbody>
                            </table>    
                            <div>
                            <?= $pager->simpleLinks() ?>
                            
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>       
     
    </body>
</html>

Feel free to share if you are still having trouble to run CodeIgniter-4 project. Please share this blog if this solution helped you to run your CodeIgniter project!

Are You Looking For Long-Term CodeIgniter Developer? Contact Now

Dhruvanshi Maharshi

Freelance Full Stack Developer

http://parinshi.com/

How to Setup and Install WordPress Project on localhost?

How to Setup and Install WordPress Project on localhost?

WordPress is widely used CMS because of its easy process of installation, setup and data management. Now WordPress is more easy to customize and manage data because of flexible and user-friendly plugins and themes like Elementor, Divi, Astra theme etc. User can easily launch their website with less effort and knowledge of coding. I will try to help all the non-tech users who can follow these steps and publish their site online.

Prior Requirements

  • PHP version 7.4 or greater.
  •  MySQL version 5.6 OR  MariaDB version 10.1 or greater.
  • Xampp Control Panel

Setup Process:

Step 1:

You need to download wordpress files from wordpress.org website. You can download WordPress from https://wordpress.org/download/ You can find download button on site like below:

Step 2:


You will receive .ZIP file of WordPress files and packages. After downloading WordPress files, you need to place that .ZIP in C:\xampp\htdocs folder (If you are working on local machine).
If you are working on live server, you need to place .ZIP file in root directory. That is, under public_html/

Step 3:

Replace folder name with your project name. Let’s assume folder name as ‘myfirstproject’


Process to connect WordPress with Database

Step 4:

Now before moving ahead for the next step, you need to start local server (Apache) and MySQL option to start.

Step 5:

Now, run the command on web browser like http://localhost/[yourprojectname]. once you run this command you can see below screen. Here my path will be like http://localhost/myfirstproject

You can select your native language from here. Default language will be English.

Step 6:

Once you will click on continue, you need to create a database from where you need you need to get database name, database username, password and database host details.

NOTE: Remember, this information will be saved in wp-config.php file which can be found here: C:\xampp\htdocs\myfirstproject\wp-config.php and you can edit them according to your database information.

Steps to create Database: (Steps for local machine)

Step 7:

Open phpmyadmin in web browser http://localhost/phpmyadmin/
Now, to create new you need to click on new button. Please find initial screen from where you can create database.

NOTE: Give proper database name that describes your project then click on ‘Create’. See below image.

Step: 8

After creating database, you need to fill the database information in wordpress like below:

NOTE: In local machine, default username is root, password should remain blank and Database Host should be localhost. See how to create and connect database on live server?
Once you can press run the installation button, your wordpress will connect with your database.

STEPS TO INSTALL WORDPRESS

Step:9

You need to provide following information:

  • Site Title – that can be your domain name or business name.
  • Username – You need to provide username for admin login. This username will be used to login your admin panel/dashboard.
  • Password: Admin login password (Don’t forget to copy password in text file)
  • EMail ID: Enter mail ID, in which you will get all update notification mails.

Step:10

Once you install WordPress, you will get success message like this and now you can login to your your admin dashboard to build/customize your website.

Ready to check your website now. URL should be like: http://localhost/myfirstproject/

Still Confused? Get Help!

WordPress is very easy to setup, install and to build a site and it is 100% FREE available. As per the latest statistics in 2021, 35% of the internet is powered by WordPress. It’s easily available by one download click. If you are still not getting output, you can contact Parinshi for detailed help.

Thank you everyone!

Dhruvanshi Maharshi

Freelance Full Stack Developer

http://parinshi.com/